一、使用子绝父相的定位实现
1.1 必须知道大盒子和小盒子的宽高
<div class="outside">
<div class="inside"></div>
</div>
<style>
.outside {
position: relative;
width: 300px;
height: 300px;
background-color: rgb(119, 197, 171);
}
.inside {
position: absolute;
width: 100px;
height: 100px;
background-color: rgb(231, 167, 186);
left: 50%;
top: 50%;
margin-left: -50px; /*小盒子宽度的一半*/
margin-top: -50px; /*小盒子高度的一半*/
}
</style>
如图所示:
1.2 大盒子和小盒子都必须有具体宽高,但可以不知道具体的值
<div class="outside">
<div class="inside"></div>
</div>
<style>
.outside {
position: relative;
width: 300px;
height: 300px;
background-color: rgb(119, 197, 171);
}
.inside {
position: absolute;
width: 100px;
height: 100px;
background-color: rgb(231, 167, 186);
top: 0;
right: 0;
bottom: 0;
left: 0;
margin: auto;
}
</style>
1.3 不需要有具体宽高或不知道具体宽高,但是要考虑兼容性
<div class="outside">
<div class="inside"></div>
</div>
<style>
.outside {
position: relative;
width: 30%; /*不需要有具体宽高*/
height: 300px;
background-color: rgb(119, 197, 171);
}
.inside {
position: absolute;
background-color: rgb(231, 167, 186);
width: 80%; /*不需要有具体宽高*/
height: 100px;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
</style>
如下图所示
二、flex布局实现
<div class="outside">
<div class="inside"></div>
</div>
<style>
.outside {
width: 30%;
height: 300px;
background-color: rgb(119, 197, 171);
display: flex;
justify-content: center; /*主轴方向(x轴方向)*/
align-items: center; /*侧轴方向(y轴方向)*/
}
.inside {
background-color: rgb(231, 167, 186);
width: 80%;
height: 100px;
}
实现简单方便,但是需要考虑兼容性
三、用Javascript的方法实现(子绝父相)
3.1 分别用外部大盒子宽高减去内部小盒子宽高的结果除以二,利用子绝父相的定位方式进行定位。
<div class="outside">
<div class="inside"></div>
</div>
<style>
.outside {
position: relative;
width: 30%;
height: 300px;
background-color: rgb(119, 197, 171);
}
.inside {
background-color: rgb(231, 167, 186);
width: 80%;
height: 100px;
}
</style>
<script>
let outside = document.querySelector('.outside')
let inside = document.querySelector('.inside')
// 表示元素的内部宽度,以像素计。该属性包括内边距 padding
let outsideW = outside.offsetWidth,
outsideH = outside.offsetHeight,
insideW = inside.offsetWidth,
insideH = inside.offsetHeight;
inside.style.position = 'absolute';
inside.style.left = (outsideW - insideW) / 2 + 'px';
inside.style.top = (outsideH - insideH) /2 + 'px';
</script>
四、table-cell
<div class="outside">
<div class="inside"></div>
</div>
<style>
.outside {
display: table-cell;
/*指定行内元素(inline)或表格单元格(table-cell)元素的垂直对齐方式。*/
vertical-align: middle;
text-align: center;
width: 300px;
height: 300px;
background-color: rgb(119, 197, 171);
}
.inside {
display: inline-block;
background-color: rgb(231, 167, 186);
width: 80%;
height: 100px;
}
</style>
此种方法需要外面大盒子宽高固定(不可为百分比),不常用到。