Daniel Herr
Daniel Herr

Reputation: 20448

Hide All Except Specific Child Element Content

How would I hide all of a certain element's contents excluding one specific child's contents?

Using display hides the child.

I want them visible and using visibility keeps the space of the hidden content.

Here is what I have:

#test1 {
  visibility: hidden
}
#test2 {
  visibility: visible
}
#test3 {
  display: none
}
#test4 {
  display: block
}
<div id="test1">
  <div id="test2">test2</div>
  test1
</div>
<div id="test3">
  <div id="test4">test4</div>
  test3
</div>

Upvotes: 0

Views: 82

Answers (2)

dippas
dippas

Reputation: 60543

  • you give a general class to the parent (if you don't to use the HTML tag), and apply it the property visibility:hidden and height:0
  • apply to all children height:inherit (so it will apply 0 as parent has it)
  • either by ID or class, whatever you feel most comfortable, you set the child you want to show visibility: visible and height:auto

.hidden {
  visibility: hidden;
  height: 0;
}
.hidden > div {
  height: inherit;
}
.hidden .show {
  visibility: visible;
  height: auto;
  border: 1px dashed red;
}
<div class="hidden" id="test1">
  <div class="show" id="test2">test2 - i'm the only one visible!</div>
  test1
</div>
<div class="hidden" id="test3">
  <div id="test4">test4</div>
  test3
</div>
<div class="hidden" id="test5">
  <div id="test6">test5</div>
  test6
</div>

Upvotes: 1

Ole Sauffaus
Ole Sauffaus

Reputation: 534

Try something like this:

#test1 > * { visibility:hidden; }
#test1 > #test2 { visibility:visible; }

#test3 > * { display:none; }
#test3 > #test4 { display:block; }
<div id="test1">
    <div id="test2">
        <p>test2</p>
    </div>
    <p>test1</p>
</div>
<div id="test3">
    <div id="test4">
        <p>test4</p>
    </div>
    <p>test3</p>
</div>

The essence here is, that you can't hide a parent, and still show a child. The parent needs to be visible, and you must instead hide the unwanted child-elements, while only showing the one you need.

Upvotes: 0

Related Questions