css layout (side by side, horizontal center, vertical horizontal center)

Preface: CSS often uses side-by-side layout

1. Side-by-side layout (float (floating) implementation)

insert image description here
1. Use float (floating)

html part

<body>
<div class="main">
<div class="left"> 左侧区域</div>
<div class="right">右侧区域</div>
<div class="clear"></div>
/div>
</body>

css part

.main .left,.main .right{
    
    
border: 1px solid #FE6464;
height: 200px;
text-align: center;
line-height: 200px;
color: #FE6464;
font-size: 30px;
}
.left {
    
    width: 48%;float: left;}
.right{
    
    width: 48%;float: right;}
.clear{
    
    clear: both;}

Disadvantages: Although float float can realize two divs side by side,
1. An empty div is needed to clear the float. Of course, other methods of clearing float can also be used, but here the float needs to be cleared so as not to affect the following layout.
2. When the width of .left and .right is fixed and the browser width becomes too narrow, .right will be squeezed below

2. Side-by-side layout (display:flex (elastic layout) implementation)

Using display:flex layout can solve these two shortcomings

.main {
    
    
display:flex
}
.left {
    
    flex:1}
.right{
    
    flex:2}

The parent element defines display:flex, and the width of the child element is defined by flex. Flex is the ratio of the parent element, as follows: 1:2
insert image description here

3. Vertical and horizontal centering of side-by-side layout (display:flex (elastic layout) implementation)

Reference article
[1] https://blog.csdn.net/qq_44983621/article/details/104768986

css part

/*父盒子*/
.testParent{
    
    
    width: 700px;
    height: 200px;
    display: flex;
    flex-direction: row; /*默认也是row可以不写*/
    background-color: #428BCA;
    align-items: center;  /*这种情况是垂直居中*/
    justify-content: center;/*这种情况是水平居中*/

}
/*子盒子*/
.test{
    
    
    width: 100px;
    height: 50px;
    background-color: aqua;
}

There are other methods in css that can also achieve vertical and horizontal centering
[1] https://blog.csdn.net/weixin_45453819/article/details/122082501
[2] https://blog.csdn.net/qq_33721778/article/ details/122165187?spm=1001.2101.3001.6650.4&utm_medium=distribute.pc_relevant.none-task-blog-2%7Edefault%7ECTRLIST%7ERate-4-122165187-blog-122082501.235%5Ev32% 5Epc_relevant_default_base3&depth_1-utm_source=distribute.pc_relevant.none- task-blog-2%7Edefault%7ECTRLIST%7ERate-4-122165187-blog-122082501.235%5Ev32%5Epc_relevant_default_base3&utm_relevant_index=5

Guess you like

Origin blog.csdn.net/qq_20236937/article/details/130411052