CSS复习–二
一、水平垂直居中的几种方式
让元素在父元素中呈现出水平垂直居中的形态,无非就 2 种情况:
- 单行的文本、inline 或者 inline-block 元素;
- 固定宽高的块级盒子;
- 不固定宽高的块级盒子;
1.1单行的文本、inline 或 inline-block 元素
水平居中
此类元素需要水平居中,则父级元素必须是块级元素(block level
),且父级元素上需要这样设置样式:
.parent {
text-align: center;
}
复制代码
垂直居中
方法一:通过设置上下内间距一致达到垂直居中的效果:
.single-line {
padding-top: 10px;
padding-bottom: 10px;
}
复制代码
方法二:通过设置 height
和 line-height
一致达到垂直居中:
.single-line {
height: 100px;
line-height: 100px;
}
1.2固定宽高的块级盒子
方法一:absolute + 负 margin
.parent {
position: relative;
}
.child {
width: 100px:height: 100px;position: absolute;left: 50%;
top:50%;
margin: -50px 00-50px;
}
方法二:absolute + margin auto
.parent {
position: relative;
}
.child {
width: 100px:height: 100px;position: absolute;ieft: O;
right: O;top: 0;bottom: O;margin: auto;
}
方法三:absolute + calc
.parert {
position: relative;
}
.child {
width: 100px;height: 100px;position: absolute;
left: calc(50%- 50px);top: calc(50%- 50px);
}
1.3不固定宽高的块级盒子
方法一:absolute + transform
.parent {
position: relative;.child {
position: absolute;left: 50%;
top: 50%;
transform: translate(-50%,-50%);
}
方法二:line-height + vertical-align
.parent {i
line-height: 150px;line-height: 150px;text-align: center;}
.child {
display: inline-block;line-height: initial;vertical-align: middle;
}
方法三:writing-mode
.parent {
writing-mode: vertical-lr;text-align: center;
}
.middle {
display: inline-block;
writing-mode: horizontal-tb;text-align: center;
width: 100%;
}
方法四:table-cell
.parent {
display: table-cell;vertical-align: middle;text-align: center;
}
.child {
display: inline-block;
}
方法五:flex
.parent {
display: flex;
justify-content: center:align-items: center;
}
方法六:grid
.parent {
display: grid;
}
.child {
justify-self: center;align-self: center;
}
二、常用布局
两栏布局(边栏定宽主栏自适应)
方法一:float + overflow(BFC 原理)
aside {
float: left;width: 200px;
}
main {
overflow: hidden;
}
方法二:float + margin
aside {
float: left;width: 200px;
}
main {
margin-left: 200px;
}
方法三:flex
.layout {
display: flex;
}
aside {
width: 200px;
}
main {
flex: 1;
}
三栏布局(两侧栏定宽主栏自适应)
方法一:圣杯布局
.layout {
padding: 0 200px;}
main {
float: left;width: 100%;}
aside {
float: left;width: 200px;
}
.left {
position: relative;ieft: -200px;
margin-left: -100%;.right {
position: relative;right: -200px;
margin-left: -200px:
}
方法二:双飞翼布局
main {
float: left;width: 100%;
}
.inner {
margin: O 200px;
}
aside {
float: left;width: 200p×;
}
.left {
margin-left: -100%;
}
.right {
margin-left: -200px;
}
方法三:flex
.layout {
display: flex;
}
aside {
width: 200px;
}
main {
flex: 1;
}
多列等高布局
方法一:padding + 负margin
.layout {
overflow: hidden;
}
section {
float: left;width: 33.33%;
padding-bottom: 1000px;margin-bottom: -1000px;
}
方法二:设置父级背景图片
.layout {
background: url(./图片地址)repeat
;background-size: 100%;
}
section {
float: left;
width: 33.33%;
}