gai*_*tat 6 javascript css css3
这个CSS:
.outer-img-wrap {
border: 2px solid gray;
margin: 1vw auto;
max-width: 192px;
text-align: center;
overflow: hidden;
}
.outer-img-wrap img {
width: auto !important;
height: auto !important;
max-width: 100%;
vertical-align: middle;
}
.inner-img-wrap {
background: #000;
border: thin solid #ff9900;
margin: 2px;
}
Run Code Online (Sandbox Code Playgroud)
应用于此HTML:
<td style="width: 25%">
<div class="outer-img-wrap">
<div class="inner-img-wrap">
<img src="http://placehold.it/64x64" />
</div>
</div>
</td>
Run Code Online (Sandbox Code Playgroud)
在适当宽度的表格单元格中生成居中的响应图像.所有图像最终都具有相同的宽度,这就是我想要的.
我也希望图像以响应的方式具有相同的高度.所以我将这个Javascript添加到页面来更新填充.
function resizeImageElements()
{
var imageElements = $(".outer-img-wrap .inner-img-wrap img");
var imageElementsMaxHeight = -1;
imageElements.map( function(index) {
// compare the height of the img element
if( $(this).height() > imageElementsMaxHeight ) {
imageElementsMaxHeight = $(this).height();
}
} );
imageElements.map( function(index) {
var computeTopBottomPadding = ( imageElementsMaxHeight - $(this).height() ) / 2;
$(this).css( {
"padding-top": computeTopBottomPadding,
"padding-bottom": computeTopBottomPadding,
} );
} );
}
resizeImageElements();
Run Code Online (Sandbox Code Playgroud)
该问题是:我能做到不Javascript代码相同的效果; 只是使用CSS?
好吧,目前还不清楚你从哪里获取这些图像。如果您能够在后端服务器中处理这些图像(例如使用 PHP、Python 或 ruby),您始终可以使用固定比例创建它们的版本,这样在前端调整大小时它们将具有相同的尺寸。这将是我最喜欢的选择。
如果您无法或不想创建图像的不同版本,我相信您最好的选择是使用带有背景图像的元素而不是图像元素本身,并使用背景大小来满足您的需求。
例如:
.outer-img-wrap {
border: 2px solid gray;
margin: 1vw auto;
max-width: 192px;
text-align: center;
overflow: hidden;
}
.outer-img-wrap .img {
display:inline-block;
position:relative;
vertical-align: middle;
width:100%;
background-position:center center;
height:50px; /* or whatever height you want, you could use % value too relative to it's parent element */
/* cross browser */
-moz-background-size:cover;
-o-background-size:cover;
-ms-background-size:cover;
-webkit-background-size:cover;
background-size:cover;
}
.inner-img-wrap {
background: #000;
border: thin solid #ff9900;
margin: 2px;
}
Run Code Online (Sandbox Code Playgroud)
应用于此html:
<td style="width: 25%">
<div class="outer-img-wrap">
<div class="inner-img-wrap">
<div class="img" style="background-image:url(http://placehold.it/64x64)"></div>
</div>
</div>
</td>
Run Code Online (Sandbox Code Playgroud)
小提琴: https: //jsfiddle.net/ybkgLq4d/14/