css中一个div在另一个div中垂直水平居中的若干种方法
css中将元素居中的方法大致有定位居中、弹性盒居中、行内块结合vertical-align以及text-align等方法。
定位居中
- 定位居中,顾名思义需要用到 “position” 属性,给父盒子加上相对定位,子盒子加上绝对定位,具体实现请看下面代码。
弹性盒居中
- 弹性盒是css3中引入的一个新属性值flex,它是一种新的布局模式flexbox布局,即伸缩布局盒模型。用来提供一个更有效的方式制定、调整和分布一个容器里的项目布局,即使他们的大小是未知或者动态的。
行内块inline-block结合vertical-align以及text-align
- 行内块元素的特殊性可以使元素设置大小,并且具有文本属性。vertical-align调节垂直方向上的对齐方式,text-align调节水平方向上的对齐方式。
具体代码如下:
<!Doctype html>
<html>
<head>
<meta charset="utf-8">
<title>无标题文档</title>
<style>
body{
padding:0;
margin:0;
}
.par{
width:400px;
height:400px;
background:#ff0;
margin-bottom:30px;
}
.son{
width:100px;
height:100px;
background:#0ff;
font-size:30px;
line-height:100px;
text-align:center;
}
/* 第一种 */
body>div:nth-child(1){
position:relative;
}
body>div:nth-child(1) .son{
position:absolute;
top:0;
left:0;
right:0;
bottom:0;
margin:auto;
}
/* 第二种 */
body>div:nth-child(2){
position:relative;
}
body>div:nth-child(2) .son{
position:absolute;
top:50%;
left:50%;
transform:translate(-50%,-50%)
}
/* 第三种 */
body>div:nth-child(3){
position:relative;
}
body>div:nth-child(3) .son{
position:absolute;
top:50%;
left:50%;
margin-top:-50px;
margin-left:-50px;
}
/* 第四种 */
body>div:nth-child(4){
display:flex;
}
body>div:nth-child(4) .son{
margin:auto;
}
/* 第五种 */
body>div:nth-child(5){
display:flex;
align-items:center;
justify-content:center;
}
/* 第六种 */
body>div:nth-child(6){
display:flex;
justify-content:center;
}
body>div:nth-child(6) .son{
align-self:center;
}
/* 第七种 */
body>div:nth-child(7){
display:table-cell;
vertical-align:middle;
text-align:center;
}
body>div:nth-child(7) .son{
display:inline-block;
}
/* 第八种 */
body>div:nth-child(8){
text-align:center;
line-height:400px;
}
body>div:nth-child(8) .son{
vertical-align:middle;
display:inline-block;
}
</style>
</head>
<body>
<div class="par">
<div class="son">1</div>
</div>
<div class="par">
<div class="son">2</div>
</div>
<div class="par">
<div class="son">3</div>
</div>
<div class="par">
<div class="son">4</div>
</div>
<div class="par">
<div class="son">5</div>
</div>
<div class="par">
<div class="son">6</div>
</div>
<div class="par">
<div class="son">7</div>
</div>
<div class="par">
<div class="son">8</div>
</div>
</body>
</html>
其中最常用的居中方法有定位居中和设置弹性盒居中。大家在使用的时候还是看个人习惯或者公司要求。
本文介绍了CSS中使一个div在另一个div内垂直水平居中的三种方法:定位居中,利用position属性实现;弹性盒居中,通过flex布局达成;以及行内块结合vertical-align和text-align进行居中对齐。这为开发者提供了灵活的布局选择。
3126

被折叠的 条评论
为什么被折叠?



