晚上好
我正在尝试在我的网站上创建一个宽度可变(最大 1024 像素)的图像“栏”。我不想拉伸(stretch)图像,而是想保持恒定的高度,并根据网站宽度向栏中添加或删除图像。
作为起点,假设所有图像都具有相同的尺寸。
我考虑过同时使用网格和 flexbox ,但不知道从哪里开始。我进行了一些搜索,但找不到任何示例作为基础。
如果可以的话,我宁愿避免使用@media
查询。
最佳答案
在最基本的情况下,您可以像这样简单地隐藏所有未显示的图像:
.photo-bar {
width: 100%;
height: 100px; /* I deliberately set the size smaller than the image height to show that it works with different image sizes. If all of the images are actually the same height then you probably want it to match the image height */
overflow: hidden;
}
.photo-bar img {
height: 100%;
/* This is to make sure you don't introduce spaces between the pictures */
display: block;
float: left;
}
<div class='photo-bar'>
<img src='http://via.placeholder.com/160x120' />
<img src='http://via.placeholder.com/160x120' />
<img src='http://via.placeholder.com/160x120' />
<img src='http://via.placeholder.com/160x120' />
<img src='http://via.placeholder.com/160x120' />
<img src='http://via.placeholder.com/160x120' />
<img src='http://via.placeholder.com/160x120' />
<img src='http://via.placeholder.com/160x120' />
<img src='http://via.placeholder.com/160x120' />
</div>
您当然可以使用 flex-direction: row
来获得更好的效果,尽管这样获得所描述的行为会更加复杂(仅显示适合的图像)。如果您想要一个具有水平滚动条的画廊,这是一个更好的选择。
.photo-bar {
display: flex;
flex-direction: row;
height: 100px;
overflow: scroll;
position: relative;
}
.photo-bar img {
height: 100%;
}
<div class='photo-bar'>
<img src='http://via.placeholder.com/160x120' />
<img src='http://via.placeholder.com/160x120' />
<img src='http://via.placeholder.com/160x120' />
<img src='http://via.placeholder.com/160x120' />
<img src='http://via.placeholder.com/160x120' />
<img src='http://via.placeholder.com/160x120' />
<img src='http://via.placeholder.com/160x120' />
<img src='http://via.placeholder.com/160x120' />
<img src='http://via.placeholder.com/160x120' />
</div>
关于css - 可变宽度的图像条,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56820642/