如果不使用 JS 解决这个问题,我似乎找不到解决方案: 我需要制作一个水平 slider ,上面有图像和一些文本。所有图像都需要调整到相同的高度,并根据宽度自动调整大小。图像下方是文本,如果图像宽度太小,文本应换行。 问题:我努力将周围元素的宽度限制为图像的宽度(同时不知道图像宽度)。 预期的结果是所有图像都相邻且没有间距(类似于谷歌图像搜索)。
我在外部元素上使用 white-space:nowrap 并在内部元素上使用 display:inline-block 以获得水平滚动。我也尝试使用 flex,但没有任何区别。
这是我的 fiddle : https://jsfiddle.net/lobin/awbL80st/
`<ul>
<li>
<div class="pic">
<img src="(url)">
</div>
<div class="text">
A longer text which should wrap to multiple lines.
</div>
</li>
<li>
...`
CSS 是
ul {
list-style:none;
white-space: nowrap;
margin:0;
padding:0;
overflow-x:scroll;
width:500px;
height:240px;
}
li {
margin:0;
padding:0;
display:inline-block;
}
.pic {
height:150px;
}
img {
height:100%;
width:auto;
}
.text {
white-space:normal;
}`
有什么想法吗?
最佳答案
将 li
设为 display:table-cell;
并添加一些 JS 代码来获取图像的 width
并将其设置为文本。
$(document).ready(function(){
var a=$("img");
var b=$('.text');
for(var i=0;i<a.length;i++){
$(b[i]).css("width",a[i].width);
}
});
ul {
list-style:none;
white-space: nowrap;
margin:0;
padding:0;
overflow-x:scroll;
width:500px;
height:240px;
}
li {
display:table-cell;
width:auto;
padding-right:10px;
}
.pic {
height:100px;
width:auto;
}
img {
height:100%;
}
.text {
white-space:normal;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<ul>
<li>
<div class="pic">
<img src="https://cdn.pixabay.com/photo/2017/05/14/14/24/grass-2312139__340.jpg">
</div>
<div class="text">
A longer text which should wrap to multiple lines.
</div>
</li>
<li>
<div class="pic">
<img src="https://cdn.pixabay.com/photo/2017/06/14/23/15/soap-bubble-2403673__340.jpg">
</div>
<div class="text">
A longer text which should wrap to multiple lines.
</div>
</li>
<li>
<div class="pic">
<img src="https://cdn.pixabay.com/photo/2017/05/04/19/32/sculpture-2284945__340.jpg">
</div>
<div class="text">
A longer text which should wrap to multiple lines.
</div>
</li>
</ul>
另一个没有 javascript 的选项是设置 li
的 display:table-cell;
属性,它将每个单元格的宽度设置为最大宽度图像的宽度.
如果对您有意义,请试试这个。
ul {
list-style:none;
white-space: nowrap;
margin:0;
padding:0;
overflow-x:scroll;
width:500px;
height:240px;
}
li {
display:table-cell;
width:auto;
padding-right:10px;
}
.pic {
height:100px;
width:auto;
}
img {
height:100%;
}
.text {
white-space:normal;
}
<ul>
<li>
<div class="pic">
<img src="https://cdn.pixabay.com/photo/2017/05/14/14/24/grass-2312139__340.jpg">
</div>
<div class="text">
A longer text which should wrap to multiple lines.
</div>
</li>
<li>
<div class="pic">
<img src="https://cdn.pixabay.com/photo/2017/06/14/23/15/soap-bubble-2403673__340.jpg">
</div>
<div class="text">
A longer text which should wrap to multiple lines.
</div>
</li>
<li>
<div class="pic">
<img src="https://cdn.pixabay.com/photo/2017/05/04/19/32/sculpture-2284945__340.jpg">
</div>
<div class="text">
A longer text which should wrap to multiple lines.
</div>
</li>
</ul>
关于html - CSS:通过不使用JS的包含图像定义元素的宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44745451/