CSS布局技巧 | 青训营

69 阅读3分钟

前言


CSS 是我们常用的重要工具,而好的页面布局和样式效果却需要日积月累,慢慢总结磨炼,这里就分享一下一些自己总结学习到的一些布局方法。

盒模型


盒模型有两种 一种是 box-sizing:border-box,一种是box-sizing:content-box,这里我们使用的是第一种box-sizing:border-box


布局


两列布局

经典的两列布局左右两列组成,其中一列宽度固定,另一列宽度自适应,两列的高度相等

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

float + margin-left/right

左列声明float:left和固定宽度,由于float使节点脱流,右列需声明margin-left为左列宽度,以保证两列不会重叠。

.container {
    width: 400px;
    height: 400px;
    }
.left {
    float: left;
    width: 100px;
    height: 100%;
    background-color: red;
    }
.right {
    margin-left: 100px;
    height: 100%;
    background-color: green;
    } 

overflow + float

左列声明同上,右列声明overflow:hidden

.container {
    width: 400px;
    height: 400px;
    }
.left {
    float: left;
    width: 100px;
    height: 100%;
    background-color: red;
    }
.right {
    overflow: hidden;
    height: 100%;
    background-color: green;
    }

flex

左列声明固定宽度,右列声明flex:1自适应宽度

.container {
    display: flex;
    width: 400px;
    height: 400px;
    }
.left {
    width: 100px;
    background-color: red;
    }
.right {
    flex: 1;
    background-color: green; }

圣杯布局以及双飞翼布局

该布局是让居中的内容区域优先渲染,即DOM节点位于前面,但是页面显示区域位于中间。 圣杯布局

父元素通过padding留出两边盒子的宽度,左边盒子通过定位移动到左边显示得区域,右边盒子通过margin-right: -200px向右移动200px到右边区域显示

<div class="container clearfix">
  <div class="center fl">中间盒子</div>
  <div class="left fl"></div>
  <div class="right fl"></div>
</div>
.container {
background-color: #ddd;
padding: 0 200px;
font-size: 40px;
/* overflow: hidden; */
}

.left {
    position: relative;
    width: 200px;
    height: 200px;
    margin-left: -100%;
    right: 200px;
    background-color: rgb(177, 156, 153);
}

.right {
    width: 200px;
    height: 200px;
    margin-right: -200px;
    background-color: thistle;
}

.center {
    width: 100%;
    height: 200px;
    background-color: turquoise;
}

.fl {
    float: left;
}

.clearfix::after {
    content: '';
    display: table;
    clear: both;
}

双飞翼布局

中间盒子多了一个子节点,通过设置中间盒子的子节点margin:200px留出左右盒子的位置,然后3个盒子都进行浮动,左盒子通过margin-left: -100%显示在左边区域,右盒子通过margin-left: -200px;显示在右边区域

<div class="fl center">
  <div class="c-inner">中间盒子</div>
</div>
<div class="fl left"></div>
<div class="fl right"></div>
  .fl {
    float: left;
  }

  body {
    font-size: 40px;
    min-width: 500px;
    background-color: #ddd;
  }

  .left {
    width: 200px;
    height: 200px;
    background-color: tomato;
    margin-left: -100%;
  }

  .right {
    width: 200px;
    height: 200px;
    background-color: thistle;
    margin-left: -200px;
  }

  .center {
    width: 100%;
    height: 200px;
    background-color: turquoise;
  }

  .c-inner {
    margin: 0 200px;
  }

结尾

以上布局使用到了float,flex,position等属性,这也是布局当中的常用属性,还有grid等很多强大的布局属性能够探索实践,希望对你有所帮助,更多的布局技巧方法还需要慢慢积累实践,一起加油!