Css布局-圣杯布局

385 阅读3分钟

在做前端的知识点总结时,发现Css布局牵连的知识点竟然如此的多,难怪布局会成为前端面试的重点。以接下来要介绍的圣杯布局为例,所涉及的知识点有float布局margin负值相对定位bfcclearfix等。

核心思想

圣杯布局用来实现PC端的的三栏布局

  • 中间区域作为内容主体,需要被优先的的加载和渲染
  • 两侧区域内容的宽度固定,中间区域内容宽度自适应
  • padding为两侧区域预留出空间
  • float布局
  • margin负值,让两侧区域与中间区域横向重叠

初步搭建框架

以左右两侧区域都为200px,中间区域自适应为例子

  • HTML代码如下
<div class="header">header</div>
<div class="container">
  <div class="main">main</div>
  <div class="left">left</div>
  <div class="right">right</div>
</div>
<div class="footer">footer</div>
  • Css代码如下
*{
    margin: 0;
    padding:0;
}
.header{
  width: 100%;
  background-color: cadetblue;
  text-align: center;
}
.container{
  padding: 0 200px 0 200px;
}
.main{
    width: 100%;
    background: chocolate;
    text-align: center;
    float: left;
}
.left{
    width: 200px;
    background-color: darkgoldenrod;
    text-align: center;
}
.right{
    width: 200px;
    background-color: darkgreen;
    text-align: center;
}
.footer{
  width: 100%;
  background-color: burlywood;
  text-align: center;
}

  • 此时效果图

调整左侧区域的位置

margin-topmargin-left为负值时,元素会向上、向左移动 margin-rightmargin-bottom为负值时,右侧元素左移、下侧元素上移 可以结合盒模型的角度进一步的理解产生这些效果的原因

  • 将左侧区域的样式改为
.left{
    width: 200px;
    float: left;
    background-color: darkgoldenrod;
    margin-left: -100%;
    /* position: relative;
    right: 200px; */
    text-align: center;
}

通过margin-left:-100%结合float:left偏移到该位置

再通过相对定位postion:relativeright:200px偏移到目标位置

调整右侧区域位置

.right{
    width: 200px;
    float: left;
    background-color: darkgreen;
    margin-right: -200px;
    text-align: center;
}

右侧区域通过margin-right:-200px结合float:left可偏移到目标区域

清除浮动

看看此时包裹main、left、right区域的父容器container因为子元素的浮动,高度为0

通过让父容器触发BFC解决

.container{
    padding: 0 200px 0 200px;
    overflow: auto;
}

手写clearfix清除浮动

.clearfix::after{
    content: '';
    display: block;
    clear: both;
}
<div class="header">header</div>
<div class="container clearfix">
    <div class="main">main</div>
    <div class="left">left</div>
    <div class="right">right</div>
</div>
<div class="footer">footer</div>

谈谈最小宽度设置问题

  • 当页面宽度小于600px时,页面会发生明显的错位
  • 看看此时left区域未使用相对定位的位置 此时container容器的content小于200px,导致右边容器的margin-left:-100%小于left自身的宽度200pxleft区域无法通过margin-left负值float:left到上面,因为margin-left此时偏移的距离不够 所以,要让两侧区域与中间区域横向重叠要满足left区域能够通过margin-left偏移超过自身宽度的大小200px,即container区域的宽度始终要 大于等于 200px才能让两侧区域与中间区域横向重叠。

计算页面最小宽度为 padding-left(200px) + padding-right(200px) + left区域(200px) = 600px

body{
    min-width: 600px;
}