大家好,又见面了,我是你们的朋友全栈君。
先给div随便设置些基本的样式,这样所得到的结果容易看出效果。
css结构:
<style type="text/css"> *{
margin: 0; height: 0; } .warp{
width: 500px; height: 500px; background-color: pink;//给个背景,结果更清晰 margin: 50px auto; } .warp .box{
width: 200px; height: 200px; background-color: green; } </style>
HTML结构:
<div class="warp">
<div class="box"></div>
</div>
给父级div设置相对定位,子元素div设置绝对定位,left、right、top、bottom都设置为0,然后将margin设置为auto即可实现。
注意:子绝父相就是 父级元素相对定位,子级元素绝对定位
.warp{
width: 500px;
height: 500px;
background-color: pink;
margin: 50px auto;
position:relative;//设置为相对定位
}
.warp .box{
width: 200px;
height: 200px;
background-color: green;
position:absolute;//设置为绝对定位
left: 0;
right: 0;
top: 0;
bottom: 0;
margin: auto;
}
给父级div设置相对定位,子元素div设置绝对定位,将left、top设置为50%;然后设置transform: translate(-50%,-50%);
即可实现。
原理:设置了left: 50%;top:50%;
之后,子元素位于如图所在位置,
此时,我们需要向左移动子级div宽度的一半,子级div所在位置如图所示
向上移动子级div高度的一半,结果如图所示
即 transform: translate(-50%,-50%);
。
.warp{
width: 500px;
height: 500px;
background-color: pink;
margin: 50px auto;
position:relative;//设置为相对定位
}
.warp .box{
width: 200px;
height: 200px;
background-color: green;
position:absolute;//设置为绝对定位
left: 50%;
top: 50%;
transform: translate(-50%,-50%);
}
子级div设置绝对定位,同样设置left: 50%; top: 50%,然后利用margin值为负时,产生的相反位移(同上过渡动画tranform
产生位移类似)。即margin-left:calc(-div自身宽度/2)
,margin-top:calc(-div自身高度/2)
,也可以自己计算margin-left 和 margin-top的值。
注意:calc()
函数,CSS3 的 calc()
函数允许我们在属性值中执行数学计算操作。
.warp{
width: 500px;
height: 500px;
background-color: pink;
margin: 50px auto;
position:relative;//设置为相对定位
}
.warp .box{
width: 200px;
height: 200px;
background-color: green;
position:absolute;//设置为绝对定位
left: 50%;
top: 50%;
margin-left:calc(-200px/2);
margin-top:calc(-200px/2);
}
给父级div设置display: flex;
将父级div元素转为弹性盒,然后设置主轴对齐方式为居中 justify-content: center;
,侧轴对齐方式为居中 align-items: center;
即可实现。
.warp{
width: 500px;
height: 500px;
background-color: pink;
margin: 50px auto;
display: flex;
justify-content: center;
align-items: center;
}
.warp .box{
width: 200px;
height: 200px;
background-color: green;
}
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/213942.html原文链接:https://javaforall.cn