首页 > 其他 > 详细

块级元素水平和垂直方向居中的方式

时间:2019-12-22 18:35:21      阅读:118      评论:0      收藏:0      [点我收藏+]

块级元素水平和垂直方向居中的方法一共三种

1.先设置块级元素的宽高,然后利用定位和外边距将元素在水平和垂直方向上居中

示例:

<style>
.father{
width: 100%;
height: 500px;
position: relative;
}
.son{
width: 100px;
height: 100px;
position: absolute;
top: 50%;
left: 50%;
margin-left: -50px;
margin-top: -50px;
background-color: red;
}
</style>
<body>
<div class="father">
<div class="son"></div>
</div>
</body>

 

2.已知元素宽高,然后将父级元素设置为弹性盒,然后设置子级元素的外边距为自动

示例:

<style>
.father{
width: 100%;
height: 500px;
display: flex;
}
.son{
width: 100px;
height: 100px;
margin: auto;
background-color: red;
}
</style>
<div class="father">
<div class="son"></div>
</div>
</body>

 
3.已知元素宽高,然后利用定位和偏移量来设置元素水平和垂直方向上居中
示例:
<style>
.father{
width: 100%;
height: 500px;
position: relative;
}
.son{
width: 100px;
height: 100px;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
background-color: red;
}
</style>
<div class="father">
<div class="son"></div>
</div>
</body>

块级元素水平和垂直方向居中的方式

原文:https://www.cnblogs.com/hg845740143/p/12080214.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!