我有一个稍微不寻常的 CSS 挑战需要克服。
我有一个两列布局,其中左列的宽度由主图像的宽度设置,而右列允许填充剩余空间。主图下方有一个容器,其自然宽度可以大于主图。但是,我希望这个 div 与主图像宽度相同,并且 overflow hidden 部分。这是我尝试这样做的努力:
.outer {
margin-right: 5px;
position: relative;
}
.left {
float: left;
}
.right {
width: auto;
overflow: hidden;
}
.contentOuter {
overflow: hidden;
}
.content {
width: 500px;
}
.inner {
background-color: grey;
color: white;
width: 100%;
height: 150px;
}
<div class="outer left">
<div class="image">
<img src="http://placehold.it/350x150" />
</div>
<div class="contentOuter">
<div class="content">
<img src="http://placehold.it/500x50" />
</div>
</div>
</div>
<div class="outer right">
<div class="inner">
Hello world!
</div>
</div>
但如您所见,.contentOuter
会延伸到其内容的宽度,无论我尝试什么。
我要注意的一个主要问题是,除了 .content
具有固定宽度外,我不希望我的 CSS 中有任何其他硬编码宽度;一切都应该是完全流畅的,列的尺寸由 .image img
的尺寸决定。
所以,我正在寻找一些视觉上看起来像这样的东西,但是 .content
上没有硬编码的 max-width
:
.outer {
margin-right: 5px;
position: relative;
}
.left {
float: left;
}
.right {
width: auto;
overflow: hidden;
}
.contentOuter {
overflow: hidden;
}
.content {
max-width: 350px; /* Hard-coded for demo purposes */
}
.inner {
background-color: grey;
color: white;
width: 100%;
height: 150px;
}
<div class="outer left">
<div class="image">
<img src="http://placehold.it/350x150" />
</div>
<div class="contentOuter">
<div class="content">
<img src="http://placehold.it/500x50" />
</div>
</div>
</div>
<div class="outer right">
<div class="inner">
Hello world!
</div>
</div>
最佳答案
一个选项,虽然这取决于您可能有的进一步要求,但它只是简单地添加到较低的 block :
position: absolute;
width: 100%;
这将它从流中移除,封闭元素将不会在调整大小时考虑其宽度,只会考虑顶部图像的宽度。 overflow: hidden
将隐藏所有溢出的内容。
缺点是封闭元素(或位置或后续元素)的高度不会考虑此元素的大小。
jsFiddle: https://jsfiddle.net/jacquesc/rsz0hb1g/
关于html - 将元素的宽度设置为兄弟的宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34898530/