水平垂直居中
行内水平居中 | 行内垂直居中 | |
---|---|---|
.parent { text-align:center; } .child { display: inline-block; } | 单行 | .parent { line-height : height } |
多行 | .parent { display: flex; flex-direction: column; justify-content: center;} | |
多行 | .parent { display: table; } .child { display: table-cell; vertical-align: middle; } |
块级水平居中 | 块级垂直居中 | |
---|---|---|
宽度确定 | .child{ width: 100px; margin:0 auto;} | .parent { position: relative; } .child { position: absolute; top: 50%; margin-top: -50px; } |
绝对定位 | .parent { position: relative; } .child { position: absolute; left: 50%; transform: translateX(-50%); } | .parent { position: relative; } .child { position: absolute; top: 50%; transform: translateY(-50%); } |
利用table | .child {display: table; margin: 0 auto; } | .parent { display: table;} .child { display: table-cell; vertical-align: middle;} |
利用flex | .parent {display: flex; justify-content:center; } | .parent { display:flex; align-items:center; } |
#container
#center
方法1:绝对定位与负边距实现(已知高度宽度)
这种方式需要知道被垂直居中元素的高和宽,才能计算出margin值,兼容所有浏览器。
css
#container {
position: relative;
}
#center {
position: absolute;
top: 50%;
left: 50%;
margin: -50px 0 0 -50px;
}
方法2:绝对定位与margin:auto(已知高度宽度)
这种方式无需知道被垂直居中元素的高和宽,但不能兼容低版本的IE浏览器。
css
#container {
position: relative;
height:100px;//必须有个高度
}
#center {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;//注意此处的写法
}
方法3:绝对定位+CSS3(未知元素的高宽)
利用Css3的transform
,可以轻松的在未知元素的高宽的情况下实现元素的垂直居中。 CSS3的transform
固然好用,但在项目的实际运用中必须考虑兼容问题,大量的hack
代码可能会导致得不偿失。
css
#container {
position: relative;
}
#center {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
方法4:flex布局
利用flex布局,其中justify-content 用于设置或检索弹性盒子元素在主轴(横轴)方向上的对齐方式;而align-items属性定义flex子项在flex容器的当前行的侧轴(纵轴)方向上的对齐方式。不能兼容低版本的IE浏览器。
css
#container {//直接在父容器设置即可
height: 100vh;//必须有高度
display: flex;
justify-content: center;
align-items: center;
}
方法5:flex/grid与margin:auto(最简单写法)
容器元素设为 flex 布局或是grid布局,子元素只要写 margin: auto 即可,不能兼容低版本的IE浏览器。
css
#container {
height: 100vh;//必须有高度
display: grid;
}
#center {
margin: auto;
}