我有一个稍微不寻常的CSS挑战需要克服。
我有两列布局,其中左列的宽度由主图像的宽度设置,右边允许填充剩余的空间。主图像下方有一个容器,其自然宽度可能大于主图像。但是,我希望这个div与主图像的宽度相同,并且要隐藏溢出。以下是我尝试这样做的努力:
.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
的尺寸确定。
所以,我正在寻找直观看起来像这样的东西,但max-width
上没有硬编码的.content
:
.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>
答案 0 :(得分:2)
一种选择,虽然这取决于您可能具有的进一步要求,但只需添加到下一个块:
position: absolute;
width: 100%;
这将它从流程中取出,并且封闭元素不会考虑其宽度,仅考虑顶部图像的大小。然后overflow: hidden
将隐藏任何溢出。
缺点是封闭元素的高度(或位置或后续元素)不会考虑该元素的大小。
答案 1 :(得分:0)
解决这个问题的一种快速方法是简单地使用一些jQuery。它只需要两行代码即可实现。
var imgWidth = $('.image').width();
$('.content').width(imgWidth);