css常见布局总结

1.单列布局
1.1普通布局(头部、内容、底部)


image.png

html代码

对应css布局

.container {
            width: 80%;
            margin: 30px auto;
            border:2px solid red;
            box-sizing: border-box;
  }
  .container header {
            width: 100%;
            height: 30px;
            background: #faa;
  }
   .container .content {
            width: 100%;
            height: 300px;
            background: #aaf;
    }
   .container footer {
            height: 50px;
            background: #afa;
    }

2.内容居中(内容区域为80%宽度,采用margin:0 auto;实现水平居中)

image.png

html代码

css 代码

.container {
  width: 100%;
  margin: 30px auto;
  border:1px solid red;
  box-sizing: border-box;
}
.container header {
  width: 100%;
  height: 30px;
  background: #faa;
}
.container .content {
  width: 80%;
  margin: 0 auto;
  height: 300px;
  background: #aaf;
}
.container footer {
  height: 50px;
  background: #afa;
}

3.三栏布局
1.采用float浮动,左右大小固定,中间自适应

image.png

html代码

css代码

.wrapper {
            width: 100%;
            margin-bottom: 30px;
            border:2px solid red;
            box-sizing: border-box;
            font-size: 0;
        }
        .wrapper .left {
            display: inline-block;
            width: 200px;
            height: 300px;
            background: #faa;
        }
        .wrapper .right {
            display: inline-block;
            width: 200px;
            height: 500px;
            background: #afa;
        }
        .wrapper .content {
            width: calc(100% - 400px);
            display: inline-block;
            height: 400px;
            background-color: #aaf;
        }

4.设置子元素相对父元素布局
说明:通过设置子元素的position: relative;然后设置子元素的left, right top,bottom可以实现子元素摆放在父级元素中的任何位置。

屏幕快照 2020-04-01 下午3.21.56.png

html代码

 

css代码

.container {
  height: 300px;
  background: red;
  /*padding: 0 300px 0;*/
}
.container .middle{
  /*float: left;*/
  position: relative;
  width: 100px;
  height: 100px;
  background: green;
  left: 50%;
  top: 100px;
}

5.圣杯布局(这两个布局非常重要,性能什么的都要比上面好很多,主要是为了让content内容区域优先加载。


image.png
 

middle写在最前面,这样网页在载入时,就会优先加载。
具体实现思路,通过给 container 左右固定的padding来预留出left和right的空间
css代码

.container {
            height: 300px;
            background: #ddd;
            padding: 0 300px 0;
        }
        .container .middle{
            float: left;
            width: 100%;
            height: 300px;
        }
        .container .left{
            float: left;
            position: relative;
            height: 300px;
            width: 300px;
            margin-left: -100%;
            left: -300px;
        }
        .container .right {
            float: left;
            position: relative;
            width: 300px;
            height: 300px;
            margin-left: -300px;
            left: 300px;
        }

说明:内部元素都是左浮动的,主要区域宽度100%;
左侧区域通过margin-left:100%;使它浮动到左方,然后更具自身定位 left:-300px;将之移动到父容器的padding中
右侧同理,只不过只需要margin自己本身的宽度。
结果:左右固定宽度300px,中间自适应

你可能感兴趣的:(css常见布局总结)