借助display布局
- 父元素开启
display:flex
布局,并设置justify-content:center
主轴的空隙分布
- 因为是单行,所以使用
align-items:center
设置侧轴上的对其方式
<body>
<style>
.a{
width: 200px;
height: 200px;
background-color: red;
display: flex;
justify-content: center;
align-items: center;
}
.a .a1{
width: 50px;
height: 50px;
background-color: green;
}
</style>
<div class="a">
<div class="a1"></div>
</div>
</body>
借助flex布局
<body>
<style>
.a{
width: 200px;
height: 200px;
background-color: red;
display: grid;
}
.a .a1{
width: 50px;
height: 50px;
background-color: green;
justify-self: center;
align-self: center;
}
</style>
<div class="a">
<div class="a1"></div>
</div>
</body>
借助绝对定位和盒子模型计算规则
margin-left + border-left + padding-lef + width + padding-right + border-right + margin-right = 父元素内容区的宽度
高度和是一样的
- 文章:
- https://www.zhihu.com/question/21644198/answer/42702524
- https://www.w3.org/TR/CSS2/visudet.html#blockwidth
<body>
<style>
.a{
width: 200px;
height: 200px;
background-color: red;
position: relative;
}
.a .a1{
width: 50px;
height: 50px;
background-color: green;
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
margin: auto ;
}
</style>
<div class="a">
<div class="a1"></div>
</div>
</body>
借助绝对定位和transform
top、left、right、bottom
设置百分比基于父元素translate
的百分比参照自身
<body>
<style>
.a{
width: 200px;
height: 200px;
background-color: red;
position: relative;
}
.a .a1{
width: 50px;
height: 50px;
background-color: green;
position: absolute;
top: 50%;
right: 50%;
left: 50%;
bottom: 50%;
transform: translate(-50%,-50%);
}
</style>
<div class="a">
<div class="a1"></div>
</div>
</body>