CSS实现元素宽高按一定比例自适应

719 阅读1分钟

想实现的效果

  • 元素保持自身宽高比例
  • 尺寸自适应
<div class="box"></div>

方法一:vw视口单位

100vw 等于视口宽度的 100% ,即 1vw 等于视口宽度的 1% 。

.box{
    width: 100%;
    height: 50vw
}

方法二: padding-bottom属性

子元素的padding和margin属性百分比都是相对于父容器的宽度而言的

// 元素的高度由padding撑开
.box {
    width: 100%;
    height: 0;
    padding-bottom: 50%;
}

当该元素是一个容器,内部还有子元素需要垂直水平居中时,需要利用定位

效果图为:

<div className="img-box" style={{backgroundImage: `url(${require("../../../assets/images/AGV-0"+ 1 +".png").default})`}}>
  <div className="text">6</div>
</div>
.img-box {
  width: 100%;
  height: 0;
  padding-bottom: 100%;
  background-repeat: no-repeat;
  background-size: cover;
  background-position: center;
  position: relative;

  .text {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    font-family: 'agencry';
    color: #00FCFF;
    font-size: 24px;
  }
}