CSS实现元素的宽高比

2019-06-133076次阅读css模块css

元素的宽高比描述了其宽度与高度之间的比例关系。两种常见的视频宽高比是4:3(20世纪的通用视频格式)和16:9(高清电视和欧洲数字电视的通用)。

 

简单粗暴height: auto

img{
  max-width: 100%;
  height: auto !important;
}

 

padding-top/bottom实现

例1:

/*padding-top = (元素高度 / 元素宽度) * 100% */
/*padding-bottom = (元素高度 / 元素宽度) * 100%*/

/*1:1宽高比*/
.gallery-image {
  background-color: red;
  width: 100%;
  padding-top: 100%;
  position: relative;
}

.gallery-image img{
  position: absolute;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
}

/*16:9宽高比*/
.gallery-image {
  padding-top: 56.25%;
}
/*4:3宽高比*/
.gallery-image {
  padding-top: 75%; 
}
/*3:2宽高比*/
.gallery-image{
  padding-top: 66.66%; 
}
/*8:5宽高比*/
.gallery-image {
  padding-top: 62.5%;
}

例2:

.gallery-image {
     width: 25%;  /* 4 columns */
     height: 0px;
     overflow: hidden;
     padding-bottom: calc(25% * .5625);  /* 16:9 */
     display: inline-block;
     position:relative;
}
.gallery-image img {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

 

CSS自定义属性

<style>
img{ 
  width:var(-image-width);
  height:calc(var(-image-width)* 3/4);
}

/*公式:高度=宽度* aspectratio(例如16 / 9,3 / 4,8 / 5等)*/
</style>

<img src="https://via.placeholder.com/3/4"  style="-image-width:800px;" alt="">

 

aspect-ratio实现

aspect-ratio定义输出设备中的页面可见区域宽度与高度的比率,本特性接受min和max前缀,因此可以派生出min-aspect-ratio和max-aspect-ratio两个媒体特性。IE不支持

.gallery-image {
     aspect-ratio: 16 / 9; /* draft spec...no currently supported */
}

.gallery-image img {
     width: 100%;
     height: 100%;
     object-fit: cover;
}
@media screen and (aspect-ratio:1680/957){ … }
@import url(example.css) screen and (max-aspect-ratio:20/11);
@media screen and (min-aspect-ratio: 9/16) {
    // 如果宽高比小于9:16的话,显示这个内容
 }

@media screen and (max-aspect-ratio: 9/16) {
    // 如果宽高比大于9:16的话,显示这个内容
 }

@media screen and (aspect-ratio: 9/16) {
    // 如果宽高比是9:16的话,显示这个内容
}
上一篇: JavaScript中私有变量实现  下一篇: HTTP Referer学习  

CSS实现元素的宽高比相关文章