CSS: hide an element when the container is too narrow to be fully visible

Suppose I have an external container with an unknown fixed width and an internal element, for example:

<div id="outer"><div id="inner">hide me when #outer is too small</div></div> 

Is there a way to make #inner completely hidden (and not just cropped) when #outer not wide enough to show it whole using pure CSS?

+8
html css
source share
3 answers

This is not possible with pure CSS, since you cannot provide conditions (unless you use IE.htc; files). To do this, you need to use JS and compare the width of both elements.

For text, you can use: text-overflow:clip|ellispis;

Edit:

 #inner { width: 100%; overflow: hidden; text-overflow: ellipsis; } 

may be useful.

EDIT:

I prepared a violin for a ramp solution. Note that text-overflow with a custom string only works in FF. In addition, text-overflow has not yet been standardized. The W3C is currently declaring it as text-overflow-mode in its working draft . See also an interesting article in MDN .

+8
source share

This is possible without JS through floats and adding an auxiliary inner element:

 <div class="outer"> <div class="helper"></div> <div class="inner">hide me when .outer is too small</div> </div> 

and css:

 .outer { overflow: hidden; } .helper { width: 1px; height: 100%; float: left; } .inner { float: left; } 

The inner element will now be wrapped under the helper if it does not match the width of the outer element, which with .helper with height: 100% and .outer with overflow: hidden will cause the inner element to not be visible.

You can remove the 1px helper width with width: 0.01px instead, but I'm not sure if this is due to browser compatibility issues.

+14
source share

Christoph's answer is probably best in the general case, but in my case I knew the text content but not the width of the container, which allowed me to add an extra layer of cheating:

Modify the HTML a bit:

 <div id="first" class="container"> <div><span>first_text_section</span></div> </div> <div id="second" class="container"> <div><span>second_text_section</span></div> </div> <div id="third" class="container"> <div><span>third_text_section</span></div> </div> 

And using the following CSS:

 .container > div { color: transparent; /* don't show the text-overflow content */ overflow: hidden; height: 1em; width: 100%; } /* use the actual text to get the measurement right for hiding */ #first > div { text-overflow: "first_text_section"; } #second > div { text-overflow: "second_text_section"; } #third > div { text-overflow: "third_text_section"; } .container > div > span { color: black; /* do show the span when possible */ } 

Then, when changing the width of the container, the full text is either hidden or shown accordingly. If the text contains more than one word, the text is hidden word by word, so you need to know something.

+1
source share

All Articles