工作生活

CSS实现自适应正方形

2019-07-01  本文已影响0人  椰果粒

情况1:实现固定宽高的正方形

div{
  width: 300px;
  height: 300px;
  background-color: red;
}

情况2:实现自适应的正方形

方式一:vw vh
1vw === 1%的宽度

div{
  width: 10vw;
  height: 10vw;
  background-color: pink;
}

方式二:将padding-bottom设置为和盒子的宽一样(百分比),高设置为0。
这是因为:padding和margin的大小是根据宽度大小设置的。

.parent{
  width: 40%;
  height: 0;
  padding-bottom: 40%;
  background-color: yellow;
}
注意:
  1. 如果没有写height:0;当有内容时,高度就会被撑大。
  2. 如果写成padding-top而不是padding-bottom,内容会出现在背景以外的下边
  3. 如果里边有子元素,因为它本身高度为0,子元素设置高度100%是没有效果的。
      解决:position:absolute; 使其脱离文档流

问题2展示(设置了padding-top):


padding-top

问题3正常情况下:

*{
  margin: 0;
  padding: 0;
}
.parent{
  width: 300px;
  height: 200px;
  background-color: red;
}
.child{
  width: 100%;
  height: 100%; 
  background-color: orange;
}
<div class="parent">
  <div class="child">子元素</div>
</div>
正常情况下

自适应情况下解决问题(脱离文档流):

.parent{
  width: 40%;
  height: 0;
  padding-bottom: 40%;
  background-color: yellow;
  position: relative;
  overflow: hidden;
}
.child{
  position: absolute;
  width: 100%;
  height: 100%;
  background-color: orange;
}
上一篇 下一篇

猜你喜欢

热点阅读