Visibility
The visibility
property controls whether to show or hide an element. When set to visible
, the element will be displayed normally.
1.visible {
2 visibility: visible;
3}
4
5.hidden {
6 visibility: hidden;
7}
8
9.collapse {
10 visibility: collapse;
11}
When set to hidden
, the element will become invisible, but the space it occupies will still be preserved.
1<div class="visible">Visible</div>
2<div class="hidden">Hidden</div>
3<div class="visible">Visible</div>
As for collapse
, different elements are treated differently. For table elements such as table rows (<tr>
) or columns, the element will become invisible, and the space it occupies will be collapsed.
1<table>
2 <tr>
3 <th>Column 1</th>
4 <th>Column 2</th>
5 <th>Column 3</th>
6 </tr>
7 <tr>
8 <td>Data 1</td>
9 <td>Data 2</td>
10 <td>Data 3</td>
11 </tr>
12 <tr class="collapse">
13 <td>Data 4</td>
14 <td>Data 5</td>
15 <td>Data 6</td>
16 </tr>
17 <tr>
18 <td>Data 7</td>
19 <td>Data 8</td>
20 <td>Data 9</td>
21 </tr>
22</table>
But for other elements, it behaves the same as hidden
.
Opacity
The opacity
property accepts a numeric value from 0
to 1
, allowing you to control the opacity of an element.
1<div></div>
1div {
2 width: 300px;
3 height: 400px;
4 background-image: url(. . .);
5 background-size: cover;
6
7 opacity: 0.5;
8}
Visibility vs. opacity vs. display: hidden
There are three different properties in CSS that can control the visibility of an element, visibility
, opacity
, and display
. Let's discuss their differences before we wrap up this lesson.
visibility
accepts three values, visible
, hidden
, and collapse
.
- When set to
visible
, the element will be displayed normally. - When set to
hidden
, the element will be hidden, but the space it occupies will be preserved.
As for collapse
, when a table row or column is set to collapse
, that row or column will be hidden, and the space it occupies will also be removed. When other elements are set to collapse
, it behaves just like hidden.
When opacity
is set to 0
, the element will be hidden, but the space it occupies will be preserved. This is just like setting visibility
to hidden
.
When opacity
is set to 1
, the element will be displayed normally, just like setting visibility
to visible
.
When setting the display
property to hidden
, it will remove the element from the DOM tree, meaning the element will be hidden, and the space it occupies will also be removed. This is kind of like setting visibility
to collapse
, but it works for all elements, not just table rows and columns.