我有一个稍微不寻常的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;
}Run Code Online (Sandbox Code Playgroud)
<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>Run Code Online (Sandbox Code Playgroud)
但正如您所看到的.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;
}Run Code Online (Sandbox Code Playgroud)
<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>Run Code Online (Sandbox Code Playgroud)
解决这个问题的一个快速方法是简单地使用一些 jQuery。只需两行代码即可实现此目的。
var imgWidth = $('.image').width();
$('.content').width(imgWidth);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2243 次 |
| 最近记录: |