两栏布局的实现方式

  1. 浮动布局:将侧边栏浮动到左侧或右侧,使主要内容区域占据剩余空间。主要内容区域使用 margin 或 padding 来避免与侧边栏重叠。

  2. 绝对定位布局:将侧边栏使用绝对定位来固定在左侧或右侧,再将主要内容区域使用 margin 或 padding 来避免与侧边栏重叠。

  3. 弹性盒模型布局:将容器设置为 flex 布局,通过设置侧边栏宽度和主要内容区域宽度的比例,来实现两栏布局。

  4. 宫格布局:使用 CSS 网格布局来将容器划分为多个单元格,然后将侧边栏放置在某一个单元格中,将主要内容区域放置在其它单元格中。

  5. table布局

  6. margin负值

 html部分:

 <div class="wrap">
        <div class="left">left</div>
        <div class="right">right</div>
 </div>


 css部分:

【方法一】:浮动布局

   .left {
        float: left;
        width: 200px;
        background-color: pink;
        height: 50px
    }
    .right {
        overflow: hidden;
        height: 50px;
        background-color: blue;
    }

 注意点:

当overflow的取值不是默认值的时候,就会创建BFC(块级格式化上下文,让元素成为隔离独立的容器,且容器内的子元素不会影响到外面的布局),从而起到一些独特的作用。

以下元素会在其内部创建BFC区域:

根元素:body
绝对定位:position 为absolute或者fixed
浮动:float 除 none 以外的值
overflow不等于visible的块盒


BFC的作用:

扫描二维码关注公众号,回复: 15500342 查看本文章

消除浮动,自动高度会计算浮动元素。
它的边框盒不会与浮动元素重叠。=>上述例子正是说明此作用
不会和它的子元素进行外边距合并。

【方法二】:绝对定位

.wrap {
    position: relative;
}
.left {
        width: 200px;
        height: 50px;
        background-color: pink;
}
.right {
        position: absolute;
        top: 0;
        left: 200px;
        height: 50px;
        background-color: blue;
}

注意点:

设置了position为absolute和fixed时元素会脱离正常文档流,不在占据空间

 方法三:弹性盒子

.wrap {
    display: flex;
}
.left {
        width: 200px;
        background-color: pink;
        height: 50px;
}
.right {
        flex: 1;
        background-color: blue;
        height: 50px;
}

  【方法四】:网格布局

.wrap {
         display: grid;
         grid-template-columns: 10px auto;
}

 方法五:table布局

   .wrap {
        width: 100%;
        display: table;
    }
    .left {
        background-color: #0f0;
        width: 200px;
    }
    .right {
        width: 100%;
        display: table-cell;
        background-color: #f00;
    }

方法六:margin负值

   .wrap {
        width: 100%;
        padding: 10px
    }
    .left {
        width: 100px;
        height: 400px;
        background-color: blue;
    }
    .right {
        width: 100%;
        height: 400px;
        margin: -400px 0 0 100px;
        background-color: green;
    }

猜你喜欢

转载自blog.csdn.net/Clover_zlx/article/details/130692484