css实现自适应正方形

这里介绍7种方法,仅供参考。

1、vm单位

<div class="square-shape">这是一个可以自适应的正方形,此法适用于移动端web页面。</div>
.square-shape {
  width: 50%;
  height: 50vw;
  border: 1px solid #f00;
}

2、padding-top实现

<div class="square-shape">这是一个可以自适应的正方形,设置高度避免被内容撑开多余的高度。奇怪的是,内容在框框外面。</div>
.square-shape {
  width: 50%;
  height: 0; 
  padding-top: 50%;
  border: 1px solid #f00;
}

3、padding-bottom实现

<div class="square-shape">这是一个可以自适应的正方形,此法很好用,有内容也是正方形。</div>
.square-shape {
  width: 30%;
  height: 0;
  padding-bottom: 30%;
  border: 1px solid #f00;
}

4、伪元素的margin-top

<div class="square-shape">这里如果有内容,就不是正方形喽,限制height也没有用。</div>
.square-shape {
  width: 100%;
  overflow: hidden;
  border: 1px solid #f00;
}
.square-shape:after {
  content: '';
  display: block;
  margin-top: 100%;
}

5、伪元素的padding-top

<div class="square-shape">这里如果有内容,就不是正方形喽。</div>
.square-shape {
  width: 30%;
  max-width: 200px;  
  border: 1px solid #f00;
}
.square-shape:after {
  content: '';
  display: block;
  padding-top: 100%;
}

6、子元素margin-top

<div class="square-shape">
  <div class="content">这是一个可以自适应的正方形</div>
</div>
.square-shape{
  overflow: hidden;
  width: 50%;
  background-color: black;
}
.content{
  margin-top: 100%;
}

7、伪元素的padding-bottom,内嵌absolute元素

<div class="square-shape">
    <div class="content">这是一个可以自适应的正方形</div>
</div>
.square-shape {
  width: 50%;
  border: 1px solid #f00;
}
.square-shape:after {
  content: '';
  display: block;
  padding-bottom: 100%;
}
.content {
  position: absolute;
  width: 100%;
  height: 100%;
}

 

转载于:https://www.cnblogs.com/camille666/p/css_square.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值