将高度设置为宽度与仅css的比率

时间:2016-10-15 17:41:24

标签: html css image size

我想使用 only CSS 为HTML中的<img>元素实现以下功能:

width: calc(100% - 20px)
height: calc(width * 0.5625) /*16:9 aspect ratio*/

互联网上有关于<div>元素及其背景的类似例子。但是对于<img>元素,更改填充不起作用

Similair示例: Maintain the aspect ratio of a div with CSS

编辑,使用jQuery可以实现上述目的:

$(".myImage/s").outerHeight($(".myImage/s").outerWidth() * 0.5625);

5 个答案:

答案 0 :(得分:4)

使用viewport-width(width: calc(100% - 20px) height: calc((100vw - 20px) * 0.5625) /*16:9 aspect ratio*/ )在height属性中定义宽度:

viewport

100vw * 100vh是网页的可见区域。

其完整尺寸为vw,其中whvw是视口尺寸单位。

因此,一个“1%”等于网页当前可见宽度的{{1}}。

更多信息可在以下网址找到:Viewport units: vw, vh, vmin, vmax

答案 1 :(得分:3)

到目前为止,建议的解决方案使用vw,只有在您希望图像填充整个页面的情况下,它才有效。

但是有一种更清洁的解决方案,可以在所有尺寸的容器中将图像长宽比保持在9/16。

HTML:

...
<div class="image image-9-16"> <!-- replace image and image-9-16 with any name you like -->
    <img src="..." />
</div>
...

CSS:

.image {
    position: relative;
    display: block;
    width: calc(100% - 20px);
    max-width: calc(100% - 20px);
    height: auto;
    max-height: 100%;
    padding: 0;
    margin: 0;
    overflow: hidden;
}

.image::before {
    display: block;
    content: "";
}

.image, .image img {
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    width: 100%;
    height: 100%;
    border: 0;
}

.image-9-16::before {
    padding-top: 56.25%;
}

并且不管容纳图像的容器的宽度如何而无需将图像作为背景图像放置都可以使用...现在,您甚至可以根据需要添加更多的长宽比...

.image-1-1::before {
    padding-top: 100%;
}

.image-3-4::before {
    padding-top: 75%;
}

.image-9-21::before {
    padding-top: 42.857143%;
}
...

答案 2 :(得分:1)

你可以使用vw(视口宽度)来做到这一点:

width: calc(100vw - 20px);
height: calc((100vw - 20px) * 0.5625); /*16:9 aspect ratio*/

如果将图像放置为,也可以使用padding-bottom方法 div的背景。

https://jsfiddle.net/m11L9kjb/1/

答案 3 :(得分:1)

这对我使用实际比率...然后我需要一个最大尺寸,所以一定要在设置高度之前设置它们:

position: relative;
margin: 0 auto;
width: 100vw;
max-width: 1080px;
max-height: 1920px;
height: calc(100vw * (16/9));

答案 4 :(得分:1)

CSS 有一个名为 aspect-ratio 的内置属性,只需在定义高度或宽度后将其分配给元素即可。 CSS-tricks 有一个例子,我在下面做了一个代码片段。

div{
  width:50vw;
  border: 2px solid black;
  border-radius: 15px;
  margin:5px;
  aspect-ratio: 16/9;
 }
<div>
</div>