Ale*_*der 6 html css size image
我想为<img>HTML中的元素实现以下功能,仅使用CSS:
width: calc(100% - 20px)
height: calc(width * 0.5625) /*16:9 aspect ratio*/
Run Code Online (Sandbox Code Playgroud)
互联网上有关于<div>元素及其背景的类似例子.但是在<img>元素的情况下,更改填充不起作用
Similair示例: 使用CSS维护div的宽高比
编辑,使用jQuery可以实现上述:
$(".myImage/s").outerHeight($(".myImage/s").outerWidth() * 0.5625);
Run Code Online (Sandbox Code Playgroud)
Hel*_*and 13
使用 viewport-width ( vw) 在 height 属性中定义宽度:
width: calc(100% - 20px)
height: calc((100vw - 20px) * 0.5625) /*16:9 aspect ratio*/
Run Code Online (Sandbox Code Playgroud)
的viewport是网页的可视区域。
它的完整大小是100vw * 100vh,其中vw和wh是视口大小单位。
因此,一个“ vw”等于1%网页当前可见宽度的 。
可以在以下位置找到更多信息:视口单位:vw、vh、vmin、vmax
小智 8
到目前为止,建议的解决方案使用 vw ,它仅在您希望图像填满整个页面时才有效。
但是有一个更干净的解决方案,可以在所有尺寸的容器中保持图像纵横比 9/16。
HTML:
...
<div class="image image-9-16"> <!-- replace image and image-9-16 with any name you like -->
<img src="..." />
</div>
...
Run Code Online (Sandbox Code Playgroud)
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%;
}
Run Code Online (Sandbox Code Playgroud)
无论容纳图像的容器的宽度如何,这都可以工作,无需将图像作为背景图像放置......现在你甚至可以根据需要添加更多的纵横比......
.image-1-1::before {
padding-top: 100%;
}
.image-3-4::before {
padding-top: 75%;
}
.image-9-21::before {
padding-top: 42.857143%;
}
...
Run Code Online (Sandbox Code Playgroud)
CSS 有一个内置属性,称为aspect-ratio在定义高度或宽度后将其分配给元素。CSS-tricks有一个例子,我在下面做了一个代码片段。
div{
width:50vw;
border: 2px solid black;
border-radius: 15px;
margin:5px;
aspect-ratio: 16/9;
}Run Code Online (Sandbox Code Playgroud)
<div>
</div>Run Code Online (Sandbox Code Playgroud)