左右布局
1,float+margin实现左右布局
float属性是将该块状区域脱离父级标签的文档流,left属性值使该区域向父级标签区域的左侧边界放置,right属性值使该区域块向父级标签的右侧边界放置。
有几个特点:
- 包裹性:可以按照区域块中子元素的实际宽度进行包裹
- 破坏性:float区域块不会被父级区域块包裹,造成前端常见的高度塌陷问题,解决办法是清除浮动(clearfix);
- 占位性:float区域会占用正常文档流位置,影响同级元素,可以使用清除浮动解决。
使用在左侧元素使用float:left,右侧元素margin:left要设置为左侧元素的宽度。
2,position+margin布局
- 设置
position:abusolute可以脱离文档流,实现左右布局,通过left&right属性进行调节。 - 父元素需要设置
position: relative
3,display: inline-block实现
- 为了简单的计算右侧盒子准确的宽度,设置了子元素的
box-sizing:border-box以及父元素的box-sizing: content-box - 设置vertical-align: top满足顶端对齐
在课上目前学到的方式,更多方式需要学习。
左中右布局
1,float+margin
- 两边固定宽度,中间宽度自适应。
- 利用
margin控制两边的间距
2,position - 左右两栏使用position进行定位,中间栏使用margin进行定位
- 设置vertical-align: top满足顶端对齐
水平居中
对于行内元素:
text-align:center;
对确定宽度的块级元素:
1,margin-left:auto; margin-right:auto;
2,position实现水平居中
position: absolute;
margin-left: -(width/2)
对于未知宽度的块级元素:
display:inline-block;
text-align:center;
垂直居中
1,绝对定位和负外边距
提前知道被居中块级元素的尺寸,否则无法准确实现垂直居中
#box {
width: 300px;
height: 300px;
background: #ddd;
position: relative;
}
#child {
width: 150px;
height: 100px;
background: orange;
position: absolute;
top: 50%;
margin: -50px 0 0 0;
line-height: 100px;
}
2,绝对定位和margin: auto
#box {
width: 300px;
height: 300px;
background: #ddd;
position: relative;
}
#child {
width: 200px;
height: 100px;
background: #A1CCFE;
position: absolute;
top: 0;
bottom: 0;
margin: auto;
line-height: 100px;
}
3,使用padding实现垂直居中
#box {
width: 300px;
background: #ddd;
padding: 100px 0;
}
#child {
width: 200px;
height: 100px;
background: #F7A750;
line-height: 50px;
}
4,使用 line-height 对单行文本进行垂直居中
#box{
width: 300px;
height: 300px;
background: #ddd;
line-height: 300px;
}
5,使用 line-height 和 vertical-align,片进行垂直居中
#box{
width: 300px;
height: 300px;
background: #ddd;
line-height: 300px;
}
#box img {
vertical-align: middle;
}
