1. 左右布局
- 为要横向布局的子元素添加
float: left;,然后对父元素添加.clearfix类
HTML
<body>
<div class="clearfix">
<div class="left"></div>
<div class="right"></div>
</div>
</body>
CSS
.clearfix{
content: '';
display: block;
clear: both;
}
.left{
float: left;
width: 100px;
height: 100px;
background-color: #ace;
}
.right{
float: left;
width: 200px;
height: 100px;
background-color: #7c7;
}

左右布局
2. 左中右布局
- 在父容器上使用
positive: relative;,子元素用position: absolute;,左右块固定了宽度,中间块可根据窗口自适应宽度。
HTML
<body>
<div class="content">
<div class="left"></div>
<div class="middle"></div>
<div class="right"></div>
</div>
</body>
CSS
.content{
border: 1px solid red;
position: relative;
height: 100px;
}
.left{
position: absolute;
width: 100px;
height: 100%;
background-color: #ace;
}
.middle{
position: absolute;
left: 100px;
right: 100px;
height: 100%;
background-color: #dad;
}
.right{
position: absolute;
right: 0;
width: 100px;
height: 100%;
background-color: #7c7;
}

左中右布局
3. 水平居中
- 为每个块级元素设置
display: inline-block;,为它们的父容器设置text-align: center;,即可使多个块级元素水平居中。
HTML
<body>
<div class="container">
<div class="child">块级元素1</div>
<div class="child">块级元素2</div>
<div class="child">块级元素3</div>
<div class="child">块级元素4</div>
</div>
</body>
CSS
div.container{
text-align: center;
border: 1px solid red;
}
div.child{
display: inline-block;
}

水平居中
4. 垂直居中
- 1)居中的元素为单行文本
.text {
line-height: 100px;
height: 100px;
}
- 把文字的 line-height 设为文字父容器的高度,适用于只有一行文字的情况。

垂直居中1
- 2)已知元素宽高
- 对父元素相对定位、子元素绝对定位后,使用
top: 50%;使元素左上角到达纵向中心位置,再为margin-top赋值负的子元素高度使整块移动至垂直居中效果。
.father {
position: relative;
height: 200px;
background-color: #ace;
}
.son {
position: absolute;
background-color: red;
width: 100px;
height: 100px;
top: 50%;
margin-top: -50px;
}

垂直居中2
5. 其他小技巧
-
.clearfix常用代码示例
.clearfix::after{
content: '';
display: block;
clear: both;
}
- div高度由其内部文档流元素的高度的总和决定,如果一行内有多个内联元素,由最高的决定。
- 内联元素从左往右流动,遇到阻碍会换行
- 块级元素从上往下流动,每块独占一行
- 内联元素(如span)高度由字体的建议行高决定
- width、height属性的使用容易引起bug
- 子元素用绝对定位,父元素用相对定位,使用绝对定位的元素会自动成为块级元素
- 使用
vertical-align: top;来解决display: inline-block;带来的宽度增加 - 设置
box-sizing: border-box;可以使为元素指定的任何内边距和边框都在已设定的宽度和高度内进行绘制,从而不引起宽高值的变形