上下垂直居中
- 效果图
我想实现的是,一个大的div嵌套两个div,这两个div,宽度都是400px,上下垂直居中对齐,如图所示.
- html
一个div中嵌套两个小div
思路:
- 大的div放两个div
- 两个div上下排列居中对齐
- 有人用float,结果成了一行
- 原理就是两个div占满一行,用margin-left来控制div的内容
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>div上下布局</title>
<link rel="stylesheet" href="css/index_div.css">
</head>
<body>
<!--思路:1.大的div放两个div
2.两个div上下排列居中对齐
3.问题:1.有人用float,结果成了一行
4.原理就是两个div占满一行,用margin-left来控制div的内容-->
<div class="content">
<div class="top"></div>
<div class="bottom"></div>
</div>
</body>
</html>
- css
- content 设置宽度100%,背景颜色,高度自动,因为嵌套的div高度不确定,所以这里设置自动
- top 设置宽度400px;高度200px,背景颜色,为了实现居中,
设置外边距margin-left:50%,这里50%不是真正居中,而是div的左边缘的点位于居中位置,不代表,整个div真正居中
为了找到小div中的中点与大div的中点重合,那么就要计算,边缘到中心点的距离是多少,也就是途中的绿色的字体,因中点到边缘点的距离正好是整个div的一半,所以整个div宽度400,除以2,等于200px,所以只要设置left:-200px,就可以实现小div的中点与大div中点恰好重合.
-
同样bottom同上,只是背景颜色不同,为了更好的区分
-
其中left,需要设置相对定位,否则没作用,position:relative;
/*div内容*/
.content{
width: 100%;
/*高度自动,因为嵌套的div高度不确定,所以这里设置自动*/
height: auto;
background-color: #5e5e5e;
}
/*顶部div*/
.top{
width: 400px;
height: 200px;
background-color: #00ffcc;
margin-left: 50%;
/*需要设置绝对定位,才能用left*/
position: relative;
/*这里需要看width多少,left的值等于width的一半*/
left: -200px;
}
/*底部div*/
.bottom{
width: 400px;
height: 200px;
background-color: blueviolet;
/*这里*/
margin-left: 50%;
position: relative;
/*这里需要看width多少,left的值等于width的一半*/
left: -200px;
}
- 最终效果
事后,大家提供了很多方法
{
display: flex;
align-items: center;
}
父元素text-align:center
子元素display: inline-block