水平居中:行内元素解决方案css
只须要把行内元素包裹在一个属性display为block的父层元素中,而且把父层元素添加以下属性便可:css3
.parent {
text-align:center;
}
水平居中:块状元素解决方案布局
.item {
/* 这里能够设置顶端外边距 */
margin: 10px auto;
}
水平居中:多个块状元素解决方案
将元素的display属性设置为inline-block,而且把父元素的text-align属性设置为center便可:flex
.parent {
text-align:center;
}
水平居中:多个块状元素解决方案 (使用flexbox布局实现)
使用flexbox布局,只须要把待处理的块状元素的父元素添加属性display:flex及justify-content:center
便可:flexbox
.parent {
display:flex;
justify-content:center;
}
垂直居中:单行的行内元素解决方案orm
全选复制放进笔记.parent {
background: #222;
height: 200px;
}it
/* 如下代码中,将a元素的height和line-height设置的和父元素同样高度便可实现垂直居中 */
a {
height: 200px;
line-height:200px;
color: #FFF;
}
垂直居中:多行的行内元素解决方案
组合使用display:table-cell和vertical-align:middle属性来定义须要居中的元素的父容器元素生成效果
,以下:io
.parent {
background: #222;
width: 300px;
height: 300px;
/* 如下属性垂直居中 */
display: table-cell;
vertical-align:middle;
}
垂直居中:已知高度的块状元素解决方案table
.item{
top: 50%;
margin-top: -50px; /* margin-top值为自身高度的一半 */
position: absolute;
padding:0;
}
垂直居中:未知高度的块状元素解决方案form
.item{
top: 50%;
position: absolute;
transform: translateY(-50%); /* 使用css3的transform来实现 */
}
水平垂直居中:已知高度和宽度的元素解决方案1
这是一种不常见的居中方法,可自适应,比方案2更智能,以下:
.item{
position: absolute;
margin:auto;
left:0;
top:0;
right:0;
bottom:0;
}
水平垂直居中:已知高度和宽度的元素解决方案2
全选复制放进笔记.item{
position: absolute;
top: 50%;
left: 50%;
margin-top: -75px; /* 设置margin-left / margin-top 为自身高度的一半 */
margin-left: -75px;
}
水平垂直居中:未知高度和宽度元素解决方案
.item{
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%); /* 使用css3的transform来实现 */
}
水平垂直居中:使用flex布局实现
.parent{ display: flex; justify-content:center; align-items: center; /* 注意这里须要设置高度来查看垂直居中效果 */ background: #AAA; height: 300px;}