前端中的左右布局实现

前端得布局中,左右布局是一种很常见布局方式,下面是我在前端工做中的几种方法:javascript

一、float实现左右布局

左右布局实现的一个有效方法是利用css中的float属性,代码以下:css

//html
 <div class="box">
   <div class="left-box"></div>
   <div class="right-box"></div>
</div>
   
//css
.box{
  width: 400px;
  height: 300px;
  background: darkgray;
}
.left-box,.right-box{
  width: 50%;
  height: 100%;
  float: left;//设置两个盒子float:left
}
.left-box{
  background: red;
}
.right-box{
  background: green;
}
复制代码

咱们很容易就获得了一个左右布局: html

但这种方法也并不是完美,须要注意浮动所致使的父元素高度塌陷的问题,这就涉及要清除浮动的问题了,清除浮动的方法也有不少,我比较推荐用伪元素清除的方法。这个会单独介绍。前端

二、 display: inline-block实现左右布局

这种方法是把子元素变为行内块元素,从而实现元素的左右排列。java

//html
 <div class="box">
    <div class="left-box"></div>
    <div class="right-box"></div>
</div>

//css
.box{
  width: 300px;
  height: 200px;
  background: darkgray;
}
.left-box,.right-box{
  width: 50%;
  height: 100%;
 display: inline-block;//子元素变为行内块
}
.left-box{
  background: red;
}
.right-box{
  background: green;
}
复制代码

可是若是直接这样写,咱们运行后会发现并不能实现左右居中,右边的盒子会直接掉下去,状况以下: 浏览器

这是由于block的元素inline-block化后,IE6/7没有换行符间隙问题,其余浏览器均有;inline的元素inline-block后,全部主流浏览器都有换行符/空格间隙问题; 即两个inline-blockb元素中间会有空隙。形成本来在一列的元素变成两列, 解决这种问题,只需在父元素添加font-size:0;便可解决:布局

.box{
  width: 300px;
  height: 200px;
  background: darkgray;
  font-size: 0;//设置字体大小为0
}
.left-box,.right-box{
  width: 50%;
  height: 100%;
 display: inline-block;
}
.left-box{
  background: red;
}
.right-box{
  background: green;
}
复制代码

三、 绝对定位实现左右布局

绝对定位也是一种解决左右布局的好方法,在父元素设置相对定位,子元素设置绝对定位:字体

//html
 <div class="box">
    <div class="left-box"></div>
    <div class="right-box"></div>
</div>

//css
.box{
  width: 300px;
  height: 200px;
  background: darkgray;
  position: relative;//父元素设置相对定位
}
.left-box,.right-box{
  position: absolute;//子元素绝对定位
  width: 50%;
  height: 100%;
}
.left-box{
  background: red;
}
.right-box{
  left: 50%;//设置left为左边盒子的宽度
  background: green;
}
复制代码

这种实现的效果和上边同样,再也不附图。spa

另外也有用table、float+margin实现的,table这种在早期开发中比较常见,在如今开发中基本销声匿迹,float+margin等实现起来比较麻烦,故不介绍。code

相关文章
相关标签/搜索