简体   繁体   English

如何在 CSS 中隐藏超出父级宽度的子元素

[英]How to hide thoes children elements that exceed the paraent's width in CSS

The parent has red dashed border, and the children elements are filled with blue.父元素有红色虚线边框,子元素用蓝色填充。 It can be implemented by inline-block , float , flex , etc.它可以通过inline-blockfloatflex等来实现。 在此处输入图像描述

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?如何使用纯 CSS 或最小 JavaScript 来实现这一点?

Setting the overflow property of the parent container to hidden can do that for you.将父容器的溢出属性设置为隐藏可以为您做到这一点。

If your html structure is static, you can try to look into media queries.如果您的 html 结构是 static,您可以尝试查看媒体查询。 Otherwise, i'm not sure it would be possible in CSS.否则,我不确定在 CSS 中是否可行。

Using overflow: hidden on your parent element will not make the last child desappear until it totaly overflow.使用溢出:隐藏在您的父元素上不会使最后一个孩子消失,直到它完全溢出。

There is a way to do this using max-width , max-height and overflow , like the example below:有一种方法可以使用max-widthmax-heightoverflow ,如下例所示:

 .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>

And here is another example using flex instead of display: inline block ;这是另一个使用flex代替display: inline block ; with max-width , max-height and overflow too也有max-widthmax-heightoverflow

 .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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM