The CSS visibility property is used to control the visibility of an element. It determines whether an element is visible or hidden on a web page. The visibility property is often used in conjunction with the display property to control the layout of a web page.
The visibility property has two possible values: visible and hidden. When the visibility property is set to visible, the element is displayed on the web page. When the visibility property is set to hidden, the element is hidden from view, but still takes up space on the web page.
Let's take a look at some examples of how the visibility property can be used in CSS:
In this example, we have a div element with the visibility property set to visible:
<div style="visibility: visible;">
This is a visible element.
</div>
The output of this code will be a visible div element that displays the text "This is a visible element."
In this example, we have a div element with the visibility property set to hidden:
<div style="visibility: hidden;">
This is a hidden element.
</div>
The output of this code will be a hidden div element that does not display the text "This is a hidden element." However, the element still takes up space on the web page.
The visibility property can also be toggled with JavaScript. In this example, we have a button that toggles the visibility of a div element:
<button onclick="toggleVisibility()">Toggle Visibility</button>
<div id="myDiv" style="visibility: visible;">
This is a visible element.
</div>
<script>
function toggleVisibility() {
var div = document.getElementById("myDiv");
if (div.style.visibility === "visible") {
div.style.visibility = "hidden";
} else {
div.style.visibility = "visible";
}
}
</script>
When the button is clicked, the toggleVisibility() function is called. This function gets the div element with the id "myDiv" and checks its current visibility property. If the visibility property is set to visible, it is changed to hidden. If the visibility property is set to hidden, it is changed to visible. This toggles the visibility of the div element on the web page.
The CSS visibility property is a useful tool for controlling the visibility of elements on a web page. It can be used to hide elements that are not needed, or to toggle the visibility of elements with JavaScript. By using the visibility property in conjunction with the display property, web developers can create complex layouts that are both functional and visually appealing.