Reputation: 30993
<div id="foo">
<a id="bar1">show me</a>
hide me
<a id="bar2">hide me too</a>
</div>
How do I use CSS (display:none;
) to only have the first a
element visible?
Upvotes: 1
Views: 187
Reputation: 253308
There's two ways that I've found to allow this, the first:
#foo {
font-size: 0;
}
#bar1 {
font-size: 16px;
}
And the second:
#foo {
font-size: 0;
}
#foo :first-child {
font-size: 16px;
}
These methods work, pretty much, by giving the font
a size of 0
, so it occupies no height, or width. And then overriding that font-size
on specific elements, to cause the text of those specified tags to be shown. The problem with, and the reason I don't like, this method is that it explicitly requires a fixed-size font (16px
in the examples) to override the inherited font-size
of 0
. Still, they both work, though the latter example is probably a tad too fragile to be trusted with dynamically generated mark-up.
Upvotes: 2
Reputation: 228152
#foo {
display: none
}
#bar1 {
display: block
}
This works, but visibility: hidden
has it's own downsides:
#foo {
visibility: hidden
}
#bar1 {
visibility: visible
}
display: inline-block
/block
is seemingly required to make this work in IE8.
That's the closest you can get without changing your HTML:
HTML:
<div id="foo">
<a id="bar1">show me</a>
<span>hide me</span>
<a id="bar2">hide me too</a>
</div>
CSS:
#foo span, #bar2 {
display: none
}
Upvotes: 2
Reputation: 16848
You can't successfully cascade a style that hides all content within a container except a specific child element.
You would need to contain the words "hide me" in a <span />
or similar in order to use something like div#foo:not(#bar1) { display: none; }
but even there I'm not sure about what browsers you need to support.
Edit
Actually, on second thought, you might get away without wrapping your text in span tags if you can get away with using the :not()
pseudo class.
Upvotes: 0
Reputation: 1385
Given that structure you really can't, since there is no way to tag the "hide me" text without hiding the container div. You'd really have to have something along the lines of:
<div id="foo">
<a id="bar1">show me<a>
<span>hide me</span>
<a id="bar2">hide me too</a>
</div>
Upvotes: 0
Reputation: 40663
You can't, since #bar1 is a child of #foo. If you want the text of foo hidden, then #bar1 will be hidden too.
Upvotes: 1