[CSS布局]简单的CSS三列布局

前言

公司终于能够上外网了,近期在搞RN的东西,暂时脑子有点晕,等过段时间再来写点总结。却是最近有个新学前端的同窗常常会问一些基础知识,工做空闲写了小Demo给他看,全是很基础的知识,纯粹是顺便记录在这里就当温故而知新吧...css

CSS布局

关于布局,咱们立刻就要想到浮动和定位,根据要实现的布局,至关于用浮动和定位等属性进行拖拽便可。如今浏览器对ie等老版本浏览器的兼容需求愈来愈低,咱们还能够采用css3的flexbox布局来设计,这个现在已是必需要掌握的一个布局方法了,尤为是在移动端很是便捷,最近正火react-native正是引入了flexbox布局,学会了这个,再去作app的开发布局也会感受爽的停不下来。html

言归正传,咱们来实现一个最简单的三列布局,须要的效果以下:前端

两边是固定的侧边栏,中间是自适应宽度的主体内容。咱们有好几种方法来实现。react

绝对定位法

绝对定位感受是新手最喜欢用的方法,无论怎么样,就是一个定位叠着一个定位,什么样子均可以定位出来。css3

  • html:
<div class="container">
  <div class="left">left</div>
  <div class="right">right</div>
  <div class="main">main</div>
</div>
  • css:
.container {
  position: relative;
  width: 100%;
  height: 800px;
  background: #eee;
}

.left, 
.right {
  height: 600px;
  width: 100px;
  position: absolute;
  top: 0;
}

.left {
  left:0;
  background: burlywood;
}

.right {
  right: 0;
  background: coral;
}

.main {
  height: 800px;
  margin: 0 110px;
  background: chocolate;
}

浮动法

浮动法跟绝对定位法同样,比较简单,可是须要注意一点就是html中main部分要写在最后。react-native

  • html:
<div class="container">
<div class="left">left</div>
  <div class="right">right</div>
<div class="main">main</div>

</div>
  • css:
.container {
  height: 800px;
  background: #eee;
}

.left,
.right {
  height: 600px;
  width: 100px;
}
.left {
  float: left;
  background: burlywood
}
.right {
  float: right;
  background: coral
}
.main {
  height: 800px;
  margin: 0 110px;
  background:chocolate
}

margin负值法

margin负值法算是一个因吹丝停的方法,我其实不多用,可是公司的不少老项目中却是用的很多,这个方法比较巧妙,在html中main部分须要嵌套一个div了,而且顺序也是在第一位,而后浮动,后面left和right部分一样浮动按照正常来讲会换行了,全部给一个负值的margin,就巧妙的达到了想要的效果。浏览器

  • html:
<div class="container">
  <div class="main">
    <div class="body">main</div>
  </div>
  <div class="left">left</div>
  <div class="right">right</div>


</div>
  • css:
.container {
  height: 800px;
  background: #eee;
}

.main {
  float: left;
  width: 100%;
  height: 800px;
}

.main .body {
  height: 100%;
  margin: 0 110px;
  background: chocolate;
}

.left {
  float: left;
  margin-left: -100%;
  width: 100px;
  height: 600px;
  background: burlywood;
}

.right {
  float: left;
  margin-left: -100px;
  width: 100px;
  height: 600px;
  background: coral;
}

flexbox布局法

flexbox布局在这个场景中其实并非最合适的,由于两边侧栏都是固定宽高,和主体部分也没有等高。不过没有关系,学会其基本用法才是最主要的,记住flexbox分为容器与子元素两部分的样式设置,容器的justify-content 和 align-items是两个最重要的属性,子元素的flex属性,集成了flex-grow,flex-shrink,flex-basis三个属性。具体的用法我前面也有一篇文章写过。同时建议参考下CSS参考手册,里面关于flex属性的两个例子很是好。app

  • html:
<div class="container">
<div class="left">left</div>
  <div class="main">main</div>
<div class="right">right</div>


</div>
  • css:
.container {
  display: flex;
  height: 800px;
  background: #eee;
}

.left {
  flex: 0 0 100px;
  height: 600px;
  background: burlywood;
}

.main {
  flex: 1 1 auto;
  margin: 0 10px;
  background: chocolate;
}

.right {
  flex: 0 0 100px;
  height: 600px;
  background: coral
}

总结

忽然写点简单的CSS知识感受神清气爽,感受找到了刚学时候的新鲜感~不限网的感受不错,之后继续在博客园逛逛写写。布局

相关文章
相关标签/搜索