常见面试题之左边固定,右边自适应布局(四种方法:负边距、flex)

这个布局是最简单的布局之一,可是网络上大可能是copy,而没有认真解释以及用新的特性实现。下面就作一个新的归纳.css

要求: 左边固定100px, 右边自适应html

左position:absolute, 右margin-left 入门写法

<div class="parent">
  <div class="l-child">左边固定1  左边固定2 左边固定3</div>
  <div class="r-child">右边自适应1 右边自适应2 右边自适应3</div>
</div>
//父元素相对定位,做为子元素绝对定位的参考
.parent{display:relative; background:#ddd }
.l-child{position:absolute; width:100px;background:#bbb }
.r-child{margin-left:100px;background:#999 }

demo展现网络

左边float,触发父元素宽度计算 入门写法

html结构同上dom

.parent{background:#ddd;overflow:hidden; }
.l-child{float:left;width:100px;background:#bbb;z-index:10000; }
.r-child{margin-left:100px;background:#999;}

demo展现布局

左右float,右边使用负边距 奇伎淫巧

这个技能要这样get:flex

  1. 父元素清除浮动code

  2. A元素宽100%不变,margin-left:-100px后,外部的文档流认为以边框为界,A减小了100px,而A是右浮动,也就是左边开始有100px空白可填充的文档流空间;htm

  3. 子元素A1是认为父元素大小没有变化,margin-left:100px后,正好等于父元素在外部空出来的文档流空间。ci

  4. B元素左浮动,且是后面的dom节点,正好占据而且覆盖A空出来的空间文档

<div class="parent">
  <div class="r-box">
    <div class="r-content">
      右边自适应1 右边自适应2 右边自适应3
    </div>
  </div>
  <div class="l-box">
    左边固定1  左边固定2 左边固定3
  </div>
</div>
.parent{background:#ddd;overflow:hidden; }
.l-box{float:left;width:100px;background:#bbb;}
.r-box{float:right;width:100%;margin-left:-100px;background:#999;}
.r-content{margin-left:100px;}

demo展现

flex布局 高大尚

父元素flex布局后,子元素默认就是弹性布局,除非你肯定子元素的弹性方式
ps:这个方法完美之处还在于,垂直方向也自动填充,轻松实现了等高布局!!
html同第一个demo

.parent{display:flex; background:#ddd }
.l-child{flex:0 0 100px; background:#bbb }
.r-child{background:#999}

demo展现

相关文章
相关标签/搜索