div layout - vertical center up and down

Center vertically

  • renderings

What I want to achieve is that a large div nests two divs, both of which have a width of 400px and are vertically centered up and down, as shown in the figure.

renderings

  • html

Two small divs nested in one div

Ideas:

  1. Large div put two divs
  2. Align two divs up and down
  3. Someone used float, and the result became a line
  4. The principle is that two divs occupy one line, and margin-left is used to control the content of the divs
<!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
  1. content Set the width to 100%, the background color, and the height automatically. Because the height of the nested div is uncertain, set the automatic height here.
  2. top set width 400px; height 200px, background color, in order to achieve centering,Detailed description

margin-left

Set the margin margin-left: 50%, where 50% is not really centered, but the point on the left edge of the div is in the center position, which does not mean that the entire div is really centered

left

In order to find the midpoint of the small div coincides with the midpoint of the large div, it is necessary to calculate the distance from the edge to the center point, that is, the green font on the way, because the distance from the midpoint to the edge point is exactly the same as the entire div Half of the div, so the width of the entire div is 400, divided by 2, which is equal to 200px, so as long as you set left: -200px, the midpoint of the small div can be exactly coincident with the midpoint of the large div.

midpoint

  1. The same bottom is the same as above, but the background color is different, in order to better distinguish

  2. Among them, left, you need to set relative positioning, otherwise it will not work, 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;
}
  • final effect

renderings

Afterwards, we provided many methods


{
  display: flex;
  align-items: center;
}


父元素text-align:center
子元素display: inline-block

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324939434&siteId=291194637