Home > Software engineering >  How to hide thoes children elements that exceed the paraent's width in CSS
How to hide thoes children elements that exceed the paraent's width in CSS

Time:11-23

The parent has red dashed border, and the children elements are filled with blue. It can be implemented by inline-block, float, flex, etc. enter image description here

I want to implement such effect: when the parent's width gets too small to contain the last children element, then the last element will be hidden.
How to implement this with pure CSS or with minimal JavaScript?

CodePudding user response:

Setting the overflow property of the parent container to hidden can do that for you.

CodePudding user response:

If your html structure is static, you can try to look into media queries. Otherwise, i'm not sure it would be possible in CSS.

Using overflow: hidden on your parent element will not make the last child desappear until it totaly overflow.

CodePudding user response:

There is a way to do this using max-width, max-height and overflow, like the example below:

.parent {
   max-width: 400px;
   max-height: 60px;
   overflow: hidden;
   border: 1px dashed #ddd;
}

.child {
   width: 100px;
   height: 50px;
   margin: 5px;
   background-color: blue;
   display: inline-block;
   color: white;
   text-align: center;
}
<p>There are 5 items here</p>
<div class="parent">
   <div class="child">1</div>
   <div class="child">2</div>
   <div class="child">3</div>
   <div class="child">4</div>
   <div class="child">5</div>
</div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

And here is another example using flex instead of display: inline block; with max-width, max-height and overflow too

.parent {
  display: flex;
  border: 1px dashed #ccc;
  max-width: 380px;
  max-height: 60px;
  overflow: hidden;
  flex-wrap: wrap;
}

.child {
  background-color: blue;
  width: 100px;
  height: 50px;
  margin: 5px;
}
<pAnother example, using flex, with 5 items too</p>
<div class="parent">
    <div class="child">1</div>
    <div class="child">2</div>
    <div class="child">3</div>
    <div class="child">4</div>
    <div class="child">5</div>
</div>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related