CSS常见布局方式

 1.左右布局(两栏均为自适应宽度)

代码如下:

.child1{
        float:left;
        background:red;
        width:50%;
        height:1000px;
    }
    .child2{
        float:left;
        background:green;
        width:50%;
        height:1000px;
    }
    .clearfix::after{
        content: '';
        display: block;
        clear: both;
    } 

给两个子元素添加float,然后给它们的父元素添加clearfix类用于清除浮动。

2.左中右布局(中间宽度自适应,侧边两栏宽度固定)

.child1{
        float:left;
        background:red;
        width:100%;
        height:1000px;
    }
    .child2{
        float:left;
        background:green;
        width:200px;
        margin-left:-100%;
        height:1000px;
    }
    .child3{
        float:left;
        background:blue;
        width:200px;
        margin-left:-200px;
        height:1000px;
    }

  1. 三个元素都设置向左浮动。
  2. 设置main宽度为100%,再设置两个侧栏的宽度。
  3. 设置 负边距,child2设置 负左边距 为100%,child3设置 负左边距 为负的自身宽度。

3.水平居中

文本和链接就直接在块级父元素上加text-align: center;

只有一个块级元素就需要设置宽度并设置左右外边距为auto,margin: 0 auto; 还需要width

     多个块元素居中

    • 就需要设置包裹多个块元素的父元素text-align: center; 然后设置其中每个块元素为display: inline-block;vertical-align: top;
    • 还可以设置包裹多个块元素的父元素display: flex; justify-content: center;
    • 如果是多个块元素垂直排列的话,就利用margin: 0 auto;


4.垂直居中

单行的内联元素或者文本、链接就使用padding-top和padding-bottom 设置为同样的值。

或者使用line-height的值和height值设置为相同。



猜你喜欢

转载自blog.csdn.net/qq_25041917/article/details/80490355
今日推荐