平时开发中经常会使用到元素居中,整理了一下平时开发中常用的元素居中方式,元素居中,首先了解块元素与行内元素
1.行内元素:
与其他行内元素并排
不能设置宽高,默认的宽度就是文字的宽度
常用的标签: span , i , u , em等
2.块级元素:
霸占一行,不能与其他任何元素并列。
能接受宽高,如果不设置宽度,那么宽度将默认变为父级的100%。
常用的标签::div , h系列 , li , dt ,dd等
3.常用居中情景
a)span在div容器中垂直居中,直接将行高设置为容器高度,span标签默认在行高中居中
<div style="background: #87CEFA;height: 100px;">
<span style="line-height: 100px;">hello 我是span元素</span>
</div>
b)div中div的元素水平居中 设置magin:0 auto 当左右两边边距为auto时,元素自动水平居中,由于div是块级元素,占用一行,故子元素div会居中
<div id="" style="background: red;" >
<div style="height: 200px;width: 200px; background: blue;margin: 0 auto;"/>
</div>
4.flex布局元素水平居中,垂直居中
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style>
.parents {
background: red;
width: 100%;
height: 100px;
/*flex 布局*/
display: flex;
/*实现垂直居中*/
align-items: center;
/*实现水平居中*/
justify-content: center;
}
.children1 {
width: 50px;
height: 50px;
background: burlywood;
}
</style>
</head>
<body>
<div class="parents">
<div class="children1"></div>
</div>
</body>
</html>