css实现自适应正方形

1、vm单位

<div class="square-shape"></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: 50%;
  height: 0;
  padding-bottom: 50%;
  border: 1px solid #f00;
}

4、伪元素的margin-top

<div class="square-shape"></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%;
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 问答题47 /72 常见浏览器兼容性问题与解决方案? 参考答案 (1)浏览器兼容问题一:不同浏览器的标签默认的外补...
    _Yfling阅读 14,684评论 1 92
  • 方案1:CSS3 vw单位 CSS3 中新增了一组相对于可视区域百分比的长度单位 vw, vh, vmin, vm...
    codeice阅读 10,078评论 0 1
  • 1. 前言 前端圈有个“梗”:在面试时,问个css的position属性能刷掉一半人,其中不乏工作四五年的同学。在...
    YjWorld阅读 10,131评论 5 15
  • 学会使用CSS选择器熟记CSS样式和外观属性熟练掌握CSS各种选择器熟练掌握CSS各种选择器熟练掌握CSS三种显示...
    七彩小鹿阅读 11,426评论 2 66
  • 文 | 若云不舒 2018年5月23日 星期三 晴 二宝很是会挑选日子,5月19的预产期,到5月20号才来到我身边...
    若云不舒阅读 2,985评论 2 1