Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS: hide element when container too narrow to let it be seen in its entirety

Tags:

html

css

Suppose I have an outer container of unknown fixed width, and an inner element, like so:

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

Is there a way I can make #inner entirely hidden (not just clipped) when #outer is not wide enough to show it in its entirety using pure CSS?

like image 581
rampion Avatar asked Mar 12 '12 14:03

rampion


People also ask

How do you hide element so it will not take up any space?

The following style rule hides an element on a web page: display: none; When you set the value of display to none, the affected element will disappear. This means the element will no longer take up any space on the web page.

How do I hide an element completely in CSS?

Completely hiding elements can be done in 3 ways: via the CSS property display , e.g. display: none; via the CSS property visibility , e.g. visibility: hidden; via the HTML5 attribute hidden , e.g. <span hidden>

How do I hide elements based on screen size?

To hide an element in a responsive layout, we need to use the CSS display property set to its "none" value along with the @media rule. The content of the second <p> element having a "hidden-mobile" class will be hidden on devices smaller than 767px.

How do you hide an element in CSS without affecting the layout?

CSS Demo: visibility To both hide an element and remove it from the document layout, set the display property to none instead of using visibility .


1 Answers

This is possible without JS through floats and adding a helper 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 wrap under the helper if it doesn't fit within the width of the outer element, which with .helper having height: 100% and .outer having overflow: hidden results in the inner element not being visible.

You could remove the 1px helper width by using width: 0.01px instead, but I'm not sure if that runs into browser compatibility issues.

like image 191
nemuri Avatar answered Nov 15 '22 20:11

nemuri