一、块级元素
1. 水平居中
-
边距margin
margin: 0 auto
-
定位position
position: absolute; left:50%; right: 50%; transform: translate(-50%)
-
浮动
float: left; margin-left: 50%; margin-right: 50%; transform: translate(-50%);
-
flex布局
html{ display: flex; justify-content:center; } .div1{ width: 200px; height: 200px; background-color: blanchedalmond; }
2. 垂直居中
-
定位position
div{ position: absolute; top: 50%; transform: translateY(-50%); }
-
flex
html{ display: flex; align-items: center; } div{ }
二、行内元素
1. 水平居中
在父级元素中使用:text-align: center
2. 垂直居中
父级元素中设置行高:
div{
height:30px;
line-height:30px
} /*DIV内的行内元素均会垂直居中*/