一、行内元素
1、行内元素的水平居中:给父级元素使用属性text-align:center
2、行内元素的垂直居中:给父级元素使用属性line-hight:父元素盒子的高度
二、块级元素
1、块级元素的水平居中:给子级元素使用属性margin:0 auto
2、行内元素的水平垂直居中,有四种方法:
html代码如下:
<body>
<div class="outer">
<div class="inner"></div>
</div>
</body>
css代码如下:
a、第一种:
.outer{
width: 500px;
height: 500px;
background-color: #ddd;
border: 1px solid red;
position: relative;
}
.inner{
width: 100px;
height: 100px;
margin:auto; /*这个不要忘了写*/
position: absolute;
top: 0px;
right: 0px;
bottom: 0px;
left: 0px;
background-color: pink;
}
b、第二种:
.outer{
width: 500px;
height: 500px;
background-color: #ddd;
border: 1px solid red;
position: absolute;
}
.inner{
width: 100px;
height: 100px;
background-color: pink;
position: absolute;
top: calc(50% - 50px);
left: calc(50% - 50px);
}
c、第三种:
.outer{
width: 500px;
height: 500px;
background-color: #ddd;
border: 1px solid red;
position: relative;
}
.inner{
width: 100px;
height: 100px;
background-color: pink;
position: absolute;
left: 50%;
top: 50%;
margin-left: -50px;
margin-top: -50px;
}
d、第四种
.outer{
width: 500px;
height: 500px;
background-color: #ddd;
border: 1px solid red;
display: flex;
justify-content: center;
align-items: center;
}
.inner{
width: 100px;
height: 100px;
background-color: pink;
}