水平垂直居中的一些方法
行内元素的水平居中
1 #container { 2 text-align: center; 3 background: red; 4 5 }
块级元素的水平居中
1 body{ 2 background: red; 3 } 4 #center { 5 background: #ccc; 6 margin: 0 auto; 7 width: 100px; 8 height: 100px; 9 text-align: center; 10 line-height: 100px; 11 }
多个块级元素的水平居中
#container { text-align: center; background: red; } .center { display: inline-block; background: #ccc; }
flex实现多个块级元素的水平居中
#container { display: flex; background: red; justify-content: space-around; }
已知高度宽度元素的水平垂直居中
1.绝对定位与负边距实现
#container { position: relative; height: 200px; background: red; } #center { width: 50px; height: 50px; background: #ccc; position: absolute; top: 50%; left: 50%; margin: -25px 0 0 -25px; font-size: 1rem; }
2. 绝对定位与margin
#container { position: relative; height: 200px; background: red; } #center { width: 50px; height: 50px; background: #ccc; position: absolute; top: 0; bottom: 0; left: 0; right: 0; margin: auto; }
未知高度和宽度元素的水平垂直居中
1.被居中的元素是inline或者inline-block元素
#container { display: table-cell; background: red; height: 100px; vertical-align: middle; text-align: center; } .center{ display: inline-block; }
2. css3的transform
#container{ position:relative; } #center{ position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); }
3. flex布局
.contianer { width: 300px; background: red; display: flex; justify-content: flex-start; flex-wrap: wrap; align-items: center; } .item { width: 40px; */ background: yellow; margin: 2px 10px; }
浙公网安备 33010602011771号