一,水平居中的方法
1、元素为行内元素,设置父元素 text-align:center
2、如果元素宽度固定,可以设置左右 margin 为 auto ;
3、如果元素为绝对定位,设置父元素 position 为 relative ,元素设
left:0;right:0;margin:auto;
4、使用 flex-box 布局,指定 justify-content 属性为 center
display 设置为 tabel-ceil
1、元素为行内元素,设置父元素 text-align:center
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
div{
background-color: aqua;
width: 300px;
height: 300px;
}
p{
text-align: center;
}
</style>
</head>
<body>
<div>
<p>我是一棵小草</p>
</div>
</body>
</html>
2、如果元素宽度固定,可以设置左右 margin 为 auto ;
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
div{
background-color: aqua;
width: 300px;
height: 300px;
}
p{
text-align: center;
margin:0 auto;
}
</style>
</head>
<body>
<div>
<p>我是一棵小草</p>
</div>
</body>
</html>
3、如果元素为绝对定位,设置父元素 position 为 relative ,元素设
left:0;right:0;margin:auto;
4、使用 flex-box 布局,指定 justify-content 属性为 center
显示图
二,垂直居中的方法
1、 将显示方式设置为表格, display:table-cell ,同时设置 vertial-align:middle(少用)
2、 使用 flex 布局,设置为 align-item:center
3、 绝对定位中设置 bottom:0,top:0 ,并设置 margin:auto
4、 绝对定位中固定高度时设置 top:50%,margin-top 值为高度一半的负值
5、 文本垂直居中设置 line-height 为 height 值
1、 将显示方式设置为表格, display:table-cell ,同时设置 vertial-align:middle
2、 使用 flex 布局,设置为 align-item:center
3、 绝对定位中设置 bottom:0,top:0 ,并设置 margin:auto
4、 绝对定位中固定高度时设置 top:50%,margin-top 值为高度一半的负值
5、 文本垂直居中设置 line-height 为 height 值
显示
第五个