目前,使用STYLE,我可以使用width: 100%和auto on height(反之亦然),但我仍然不能将图像约束到特定的位置,要么太宽,要么太高,分别。
什么好主意吗?
目前,使用STYLE,我可以使用width: 100%和auto on height(反之亦然),但我仍然不能将图像约束到特定的位置,要么太宽,要么太高,分别。
什么好主意吗?
当前回答
使用JQuery,因为CSS是一个普遍的误解(这里关于简单设计目标的无数问题和讨论表明了这一点)。
用CSS做你想做的事情是不可能的:图像的宽度应该是100%,但如果这个宽度导致高度太大,max-height应该应用-当然正确的比例应该被保留。
其他回答
几年后,在寻找同样的需求时,我发现了一个使用background-size的CSS选项。
它应该可以在现代浏览器(IE9+)中运行。
<div id="container" style="background-image:url(myimage.png)">
</div>
以及风格:
#container
{
width: 100px; /*or 70%, or what you want*/
height: 200px; /*or 70%, or what you want*/
background-size: cover;
background-position: center;
background-repeat: no-repeat;
}
参考资料:http://www.w3schools.com/cssref/css3_pr_background-size.asp
demo: http://www.w3schools.com/cssref/playit.asp?filename=playcss_background-size
也有同样的问题。对我来说,问题是高度属性也已经在其他地方定义,像这样固定它:
.img{
max-width: 100%;
max-height: 100%;
height: inherit !important;
}
简单的解决方案:
min-height: 100%;
min-width: 100%;
width: auto;
height: auto;
margin: 0;
padding: 0;
顺便说一下,如果你想把它放在父div容器的居中,你可以添加这些css属性:
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
它应该真的像预期的那样工作:)
通过将CSS的max-width属性设置为100%,图像将填充它的父元素的宽度,但不会呈现比它的实际大小更大,从而保持分辨率。
将height属性设置为auto可以保持图像的纵横比,使用这种技术可以覆盖静态高度,并使图像能够在各个方向上按比例伸缩。
img {
max-width: 100%;
height: auto;
}
我将此用于高度和宽度固定的矩形容器,但图像大小不同。
img {
max-width: 95%;
max-height: 15em;
width: auto !important;
}