这codepen将明确我要做什么:
HTML:
<div class="slider-container">
<div class="table">
<div class="row">
<div class="cell">
<img src="https://images.robertharding.com/preview/RM/RH/VERTICAL/983-675.jpg">
</div>
<div class="padding-cell"></div>
<div class="cell">
<img src="https://images.robertharding.com/preview/RM/RH/VERTICAL/983-675.jpg">
</div>
<div class="padding-cell"></div>
<div class="cell">
<img src="https://images.robertharding.com/preview/RM/RH/VERTICAL/983-675.jpg">
</div>
</div>
</div>
</div>
CSS:
.slider-container {
left: 4.5em;
right: 4.5em;
position: fixed;
top: 4.5em;
height: calc(100vh - 9em);
}
.slider-container .table {
display: table;
height: inherit;
width: 100%;
}
.slider-container .table .row {
display: table-row;
width: 100%;
height: inherit;
vertical-align: middle;
text-align: center;
}
.slider-container .table .row .padding-cell {
display: table-cell;
height: inherit;
width: 1.5em;
}
.slider-container .table .row .cell {
display: table-cell;
height: inherit;
vertical-align: middle;
}
.slider-container .table .row .cell img {
max-height: 100%;
max-width: 100%;
}
https://codepen.io/simonhrogers/pen/WJJVgL
当图像的纵横比特别高,或者屏幕特别压扁时,每张图像之间的间隙将开始拉伸(stretch)得比它们之间指定的填充单元格的宽度宽得多。我怎样才能防止这种行为,以便图像始终仅由填充单元格的宽度分隔?
如果太靠近屏幕的顶部/底部或两侧,我仍然需要缩小图像;就像我在这里所做的那样,但它们之间有一个固定宽度的间隙,而不是那个也改变了。
最佳答案
您可以通过对代码进行一些小的更改来获得所需的行为:
首先为您的图像设置 width:100%
。
其次在你的类 padding-cell
中设置一个固定的填充,单位为 px
或 rem
.slider-container {
left: 4.5em;
right: 4.5em;
position: fixed;
top: 4.5em;
height: calc(100vh - 9em);
}
.slider-container .table {
display: table;
height: inherit;
width: 100%;
}
.slider-container .table .row {
display: table-row;
width: 100%;
height: inherit;
vertical-align: middle;
text-align: center;
}
.slider-container .table .row .padding-cell {
display: table-cell;
height: inherit;
width: 20px;
}
.slider-container .table .row .cell {
display: table-cell;
height: inherit;
vertical-align: middle;
}
.slider-container .table .row .cell img {
max-height: 100%;
max-width: 100%;
width: 100%;
}
<div class="slider-container">
<div class="table">
<div class="row">
<div class="cell">
<img src="https://images.robertharding.com/preview/RM/RH/VERTICAL/983-675.jpg">
</div>
<div class="padding-cell"></div>
<div class="cell">
<img src="https://images.robertharding.com/preview/RM/RH/VERTICAL/983-675.jpg">
</div>
<div class="padding-cell"></div>
<div class="cell">
<img src="https://images.robertharding.com/preview/RM/RH/VERTICAL/983-675.jpg">
</div>
</div>
</div>
</div>
尽管您可以使用flexbox
更轻松地实现布局。
关于html - 如何在水平和垂直居中的多个图像之间实现固定宽度间距,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50307369/