元素水平居中
正常的margin后面是跟padding一样的,跟着4个参数,margin: 0 auto;0为上下外间距为0px auto代表左右自动适应。
居中不好使的原因:
1、元素没有设置宽度,没有宽度怎么居中嘛!
2、设置了宽度依然不好使,你设置的是行内元素吧,行内元素和块元素的区别以及如何将行内元素转换为块元素
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
#box{
width:200px;
height: 200px;
background-color: orange;
margin:0 auto
}
#context{
line-height: 80px;
background-color: red;
width: 80px;
height:80px;
text-align: center;
margin: 0 auto;
}
</style>
</head>
<body>
<div id="box">
<div id="context">呜呜呜</div>
</div>
</body>
</html>
元素水平垂直居中
方案1:position 元素已知宽度
父元素设置为:position: relative;
子元素设置为:position: absolute;
距上50%,据左50%,然后减去元素自身宽度的距离就可以实现
方案2:position transform 元素未知宽度
如果元素未知宽度,只需将上面例子中的margin: -50px 0 0 -50px;替换为:transform: translate(-50%,-50%);
方案3:flex布局
.box {
background-color: #FF8C00;
width: 300px;
height: 300px;
display: flex;//flex布局
justify-content: center;//使子项目水平居中
align-items: center;//使子项目垂直居中
}