Show Children when Parent is Hidden with CSS

04 April 2024

Updated: 08 April 2024

When working with HTML we sometimes have a case where we want to view child items of an HTML element while the parent element itself is hidden

Normally when trying to hide or show some elements, we would apply display:none and move on. However, we may run into a case where we want to make a specific child visible while keeping the remaining content hidden, so, we might try to add the following to the child display:block.

We will quickly see that this solution doesn’t work. Another thing we might trying to play with the opacity of the items but this doesn’t really solve our problem either

The solution to this is the visibility property

According to the MDN Documentation on Visibility: “The visibility CSS property shows or hides an element without changing the layout of a document.”

The MDN definition brings up an important note - the visibility property does not change the layout of the document - this means the hidden elements will still take up space on the screen, which is different to the behaviour of display:none. However, we can mitigate that in other ways if we need to deepending on what we’re trying to do

We can use the visibility property to get what we want. For our example let’s use a ol with some children, however, we want anything inside of our list to be hidden other than a specific child

The HTML we have is as follows:

css-visibility/CSSVisibility.astro
1
<div class="example">
2
<div>before hidden</div>
3
4
<ol class="hide">
5
<li>Item 1</li>
6
<li class="show">Item 2</li>
7
<li>Item 3</li>
8
</ol>
9
10
<div>after hidden</div>
11
</div>
12
13
<style>
14
.hide {
15
visibility: hidden;
16
}
17
18
.show {
19
visibility: visible;
20
}
21
22
.example {
23
padding: 1rem;
24
background-color: var(--color-on-base);
25
color: var(--color-base);
26
}
27
</style>
before hidden
  1. Item 1
  2. Item 2
  3. Item 3
after hidden

It’s also important to note that the content before and after the list are not visible but they still take up space

You can play around with the CSS properties below to see how the influence the overall styling:

css-visibility/css-visibility.css
1
.hide {
2
display: var(--hide-display);
3
visibility: var(--hide-visibility);
4
}
5
6
.show {
7
display: var(--show-display);
8
visibility: var(--show-visibility);
9
}
10
11
.example {
12
padding: 1rem;
13
background-color: var(--color-on-base);
14
color: var(--color-base);
15
}