CSS简单布局

1. 左右布局

利用float完成左右布局,由于用了float出现了父元素高度崩塌BUG,要用cf解决BUG。

 <div class="father cf">
    <div class="son-left">1</div>
    <div class="son-right">2</div>
  </div>
.father {
  border:5px black solid;
  background: #ccc;
}
.son-left {
  background: pink;
  float:left;
  height: 100px;
  width: 40%;
}
.son-right {
  background: skyblue;
  float:right;
  height: 200px;
  width: 60%;
}
.cf::before,::after {
    content: '';
    display: block;
}
.cf:after {
    clear: both;
}
左右布局

2. 左中右布局

2.1 全部float

与左右布局同样,额外补充中部盒子就可以

2.2 子绝+父相

左右用position: absolute;中用左右margin,此时触发absolute的BUG,父元素添加position: relative;解决BUG。

<div class="father">
  <div class="son-left">1</div>
  <div class="son-middle">2</div>
  <div class="son-right">3</div>
</div>
.father {
  border:5px black solid;
  background: #ccc;
  position: relative;
}
.son-left {
  background: pink;
  position: absolute;
  left:0;
  top:0;
  height: 100px;
  width: 100px;
}
.son-right {
  background: skyblue;
  position: absolute;
  right:0;
  top:0;
  height: 100px;
  width: 100px;
}
.son-middle {
  margin-left:100px;
  margin-right:100px;  
  height: 100px;
  background: hotpink;
}

3 水平居中&垂直居中

3.1 左右margin

子元素只能是block才能使用

<div class="father">
  <div class="son">2</div>
</div>
.father {
  border:5px black solid;
  margin:100px;
  background: #ccc;
}
.son {
  display:block;
  margin:20px auto;
  width: 100px;
  height: 100px;
  border:1px red solid;
  background-color: pink;
}
左右margin

3.2 更改定位

相对于左右margin,inline-block可以用更改定位,利用left和top:50%,再用transform: translate(-50%,-50%)回调。

<div class="father">
  <div class="son">
    434343
  </div>
.father {
  border:5px black solid;
  margin:100px;
  background: #ccc;
  height: 300px;
}
.son {
  position: relative;
  display: inline-block;
  top:50%;
  left:50%;
  width: 100px;
  height: 100px;
  border:1px red solid;
  background-color: pink;
  transform: translate(-50%,-50%)
}
更改定位

3.3 父元素text-align:text

子元素只能是inline和inline-block,非常容易出现BUG,慎用。

<div class="father">
  <div class="son">
  </div>
</div>
.father {
  border:5px black solid;
  margin:100px;
  background: #ccc;
  text-align:center;
}
.son {
  display:inline-block;
  width: 100px;
  height: 100px;
  border:1px red solid;
  background-color: pink;
}
父元素text-align:text

4.其他

4.1 clear:both清除浮动

由于浮动,浮动的脱标,父元素失去高度出现崩塌,父元素之后的元素也会紧跟着浮动,利用clear:both来消除bug。

代码见1.左右布局

4.2 待补充

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容