7

I want to make the following inner span disappear, if it's an only child:

<div class="foo">
  <span></span>  
</div>

i.e. the selector should not work in this case:

<div class="foo">
  <span></span>  
  Some text
</div>

I tried :only-child and :last-child which don't work, I assume because of that "Some text" text.

h bob
  • 3,610
  • 3
  • 35
  • 51
  • 1
    Your question is not clear enough. Are you asking how to hide all the elements inside the div with class 'foo'? If that is what you mean why don't you use: div.foo:empty { display: none } and hide the whole thing if empty? – Ionut Necula Oct 26 '15 at 09:16
  • @Ionut Yes it wasn't clear enough, I updated it. – h bob Oct 26 '15 at 09:19
  • 1
    Have you tried .foo span:empty:first-child ? Also, in your code the span it's always the only child. The 'Some text' text is not a child. – Ionut Necula Oct 26 '15 at 09:21
  • @Ionut If there is "Some text" then I don't want to hide it. So I tried `span:last-child` which doesn't work, it always hides it. – h bob Oct 26 '15 at 09:25
  • @Ionut Yes that's what I thought... the text is not an element. So is there any way to deal with that? – h bob Oct 26 '15 at 09:25
  • 2
    I think this cannot be done with only CSS. You should use jQuery or JavaScript. – Ionut Necula Oct 26 '15 at 09:25
  • only the span should be invisible or both text and span? – Shuvro Oct 26 '15 at 09:58
  • 2
    A pure CSS solution would need an extra element around `Some text` and existing span coming after this extra element (then reordered with flexbox or float or whatever). Then you could select the latter whether or not it comes after the extra element e.g. it's the :first-child or not – FelipeAls Oct 26 '15 at 10:34

1 Answers1

1

I think this cannot be done with only CSS. You should use jQuery or JavaScript by making some conditions.

if ($(".foo").text().length < 1 && $('.foo span').is(':empty')) {
    //hide your element here
    $('.foo').hide();
}
BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
Ionut Necula
  • 11,107
  • 4
  • 45
  • 69