文章目录
前言
我们经常在项目中会遇到这样一个问题,就是需要使一个盒子,水平垂直居中在另一个盒子中,那么今天为大家整理了一下相关垂直居中的各个方法!
一、使用transform属性
使用transform属性中的translate方法将子盒子进行移动,注意,这需要事先知道子元素和父元素的尺寸以计算出移动的距离。让子元素向左和向上方各移动其本身宽高的一半。代码中的transform: translate(175px, 175px);就是父元素的宽(高)的一半 200px - 子元素宽(高)的一半 25px = 175px
<body>
<div id="ParentBox">
<div id="Subbox"></div>
</div>
</body>
<style>
body {
margin: 0;
padding: 0;
}
#ParentBox {
width: 400px;
height: 400px;
background-color: #ccc;
}
#Subbox {
width: 50px;
height: 50px;
background-color: rgb(237, 145, 40);
border-radius: 50%;
transform: translate(175px, 175px);
}
</style>
二、flex布局(方法一)
给父元素设置display:flex开启弹性盒,然后将justify-content(主轴排列方式)和align-items(侧周排列方式)属性都设为center,可以实现元素水平垂直居中显示。
<body>
<div id="ParentBox">
<div id="Subbox"></div>
</div>
</body>
<style>
body {
margin: 0;
padding: 0;
}
#ParentBox {
width: 400px;
height: 400px;
background-color: #ccc;
display: flex;
justify-content: center;
align-items: center;
}
#Subbox {
width: 50px;
height: 50px;
background-color: rgb(237, 145, 40);
border-radius: 50%;
}
</style>
三、flex布局(方法二)
给父元素设置display:flex开启弹性盒,然后给子元素设置margin:auto,也可以实现元素的水平垂直居中
<body>
<div id="ParentBox">
<div id="Subbox"></div>
</div>
</body>
<style>
body {
margin: 0;
padding: 0;
}
#ParentBox {
width: 400px;
height: 400px;
background-color: #ccc;
display: flex;
}
#Subbox {
width: 50px;
height: 50px;
background-color: rgb(237, 145, 40);
border-radius: 50%;
margin: auto;
}
</style>
四、使用position属性(方法一)
给父元素设置position属性(注意:不能设置默认值),然后将子元素的position属性设为fixed或absolute,再后将子元素的top、bottom、left、right属性都设为0,同时margin设为auto即可实现
<body>
<div id="ParentBox">
<div id="Subbox"></div>
</div>
</body>
<style>
body {
margin: 0;
padding: 0;
}
#ParentBox {
width: 400px;
height: 400px;
background-color: #ccc;
position: relative;
}
#Subbox {
width: 50px;
height: 50px;
background-color: rgb(237, 145, 40);
border-radius: 50%;
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
margin: auto;
}
</style>
五、使用position属性(方法二)
给父元素设置position属性(注意:不能设置默认值),然后将子元素的position属性设为fixed或absolute,将子元素的top、bottom、left、right属性都设为50%,在给子元素加上transform: translate(-50%,-50%)即可实现
<body>
<div id="ParentBox">
<div id="Subbox"></div>
</div>
</body>
<style>
body {
margin: 0;
padding: 0;
}
#ParentBox {
width: 400px;
height: 400px;
background-color: #ccc;
position: relative;
}
#Subbox {
width: 50px;
height: 50px;
background-color: rgb(237, 145, 40);
border-radius: 50%;
position: absolute;
top: 50%;
bottom: 50%;
left: 50%;
right: 50%;
transform: translate(-50%,-50%);
}
</style>
六、使用display属性
先给子元素设置display: inline-block,变成行内元素,然后给父元素设置text-align: center且line-height等于height即可实现
<body>
<div id="ParentBox">
<div id="Subbox"></div>
</div>
</body>
<style>
body {
margin: 0;
padding: 0;
}
#ParentBox {
width: 400px;
height: 400px;
background-color: #ccc;
line-height: 400px;
text-align: center;
}
#Subbox {
width: 50px;
height: 50px;
background-color: rgb(237, 145, 40);
border-radius: 50%;
display: inline-block;
}
</style>
总结
元素水平垂直居中是面试过程中经常考的点,还是需要多多记忆,本篇文章仅仅是自己的学习笔记,希望可以帮助到你~