方式一:通过外边距调整,根据父子元素的宽高来计算外边距的值。(父子都是块级元素)
注意:如果两个盒子是嵌套关系, 有时候设置了里面一个盒子(子元素)顶部的外边距, 外面一个盒子(父元素)也会被顶下来。
解决办法:https://blog.csdn.net/zyj123__/article/details/106906240
<style>
.div1{
width: 200px;
height: 200px;
background-color: darkcyan;
overflow: hidden;
}
.div2{
width: 60px;
height:60px;
margin-top: 70px;
margin-left: 70px;
background-color:darkgoldenrod;
}
</style>
<body>
<div class="div1">
<div class="div2"></div>
</div>
方式二:给父元素设置绝对定位,子元素设置相对定位(子绝父相),然后给子元素设置top:0、bottom:0、left:0,right:0,margin:auto
<style>
.div1{
width: 200px;
height: 200px;
background-color: darkcyan;
position: relative;
}
.div2{
width: 60px;
height:60px;
background-color:darkgoldenrod;
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
margin: auto;
}
</style>
</head>
<body>
<div class="div1">
<div class="div2"></div>
</div>
效果如上图
方式三:给父元素设置绝对定位,子元素设置相对定位(子绝父相),然后给子元素设置top:50%、left:50%、transform: translate(-50%,-50%)。(translate(-50%,-50%)可换成margin-left:-元素宽度的一半,margin-top:-元素高度的一半;)
<style>
.div1{
width: 200px;
height: 200px;
background-color: darkcyan;
position: relative;
}
.div2{
width: 60px;
height:60px;
background-color:darkgoldenrod;
position: absolute;
top:50%;
left: 50%;
transform: translate(-50%,-50%);
}
</style>
</head>
<body>
<div class="div1">
<div class="div2"></div>
</div>
效果如上图
方式四: 把父元素声明为伸缩盒布局,即display:flex;然后给父元素设置justify-content: center、 align-items: center;
<style>
.div1{
width: 300px;
height: 300px;
background-color: darkcyan;
/* 伸缩盒布局 display我们是在父容器中进行声明的 */
display: flex;
justify-content: center; /* 水平居中 */
align-items: center; /* 垂直居中 */
}
.div1 div{
width: 60px;
height:60px;
}
</style>
<div class="div1">
<div style="background-color: bisque;"></div>
<div style="background-color: blueviolet;"></div>
</div>