CSS自适应布局(左右固定 中间自适应或者右侧固定 左侧自适应)

来源:互联网 发布:齐天大圣 知乎 编辑:程序博客网 时间:2024/05/21 09:43

来自:http://www.2cto.com/kf/201312/266639.html

经常在工作中或者在面试中会碰到这样的问题,比如我想要个布局 右侧固定宽度 左侧自适应 或者 三列布局 左右固定 中间自适应的问题。

 下面我们分别来学习下,当然我也是总结下而已,有如以下方法:
  =====================================================================
     一: 右侧固定宽度 左侧自适应
 
  第1种方法:左侧用margin-right,右侧float:right  就可以实现。
 
    HTML代码可以如下写:
    <div class="box-left">
        <a href="" target="_blank">我是龙恩</a>
    </div>
 
  <div class="box-right">
        <a href="" target="_blank">我是龙恩</a>
    </div>

  CSS代码可以如下写:
    .box-left{height:300px;margin-right:300px;background:#DDD;}
    .box-right{width:300px;height:300px;float:right;background:#AAA;}
 
    如上代码就可以实现效果。

    第2种方法:左侧同样用margin-right  右侧采用绝对定位 如下代码所示:
 
    HTML代码如下:
 
    <div class="bd">
        <div class="bd-left">
            <a href="" target="_blank">我是龙恩</a>
        </div>
        <div class="bd-right">
            <a href="" target="_blank">我是龙恩</a>
        </div>
    </div>
 
 CSS代码如下:
 
 .bd{position:relative;}
 .bd-left{height:300px;;margin-right:300px;background:#DDD;}
 .bd-right{width:300px;height:300px;position:absolute;top:0;right:0;background:#AAA;}
 
 第3种方法:右侧浮动 且 用负margin值
 
 HTML代码如下:
 
 <div class="wrap">
        <div class="wrap-left">
            <div class="left-con">
                <a href="" target="_blank">我是龙恩</a>
            </div>
        </div>
        <div class="wrap-right">
            <a href="" target="_blank">我是龙恩</a>
        </div>
    </div>
 
  CSS代码如下:
 
  .wrap{overflow:hidden;background:#EEE;}
  .wrap-right{width:300px;position:relative;float:right;margin-left:-300px;background:#AAA;}
  .wrap-left{width:100%;float:left;}
  .left-con{margin-right:300px;background:#DDD;}
  .left-con,.wrap-right{height:300px;}
 
以上是我总结的三种html css 两列布局方法(左侧自适应 右侧固定),如有不足的地方 请大家多多指教。下面我们来看看三列布局(左右固定 中间自适应的情况)。
 
 =====================================================================
 二:左右固定 中间自适应的情况
 
 我目前总结了2种方法 如下:
 
 第一种:左右侧采用浮动 中间采用margin-left 和 margin-right 方法。
 
 代码如下:
 
   <div style="width:100%; margin:0 auto;"> 
       <div style="width:200px; float:right; background-color:#960">这是右侧的内容 固定宽度</div>
       <div style="width:150px; float:left; background:#6FF">这是左侧的内容 固定宽度</div>
       <div style="margin-left:150px;margin-right:200px; background-color:#9F3">中间内容,自适应宽度</div>
    </div>
 
 第二种:左右两侧采用绝对定位 中间同样采用margin-left margin-right方法:
 
 HTML代码如下:
 
 <div class="l-sidebar"></div>
 <div class="mainbar"></div>
 <div class="r-sidebar"></div>
 
CSS代码如下:
 
 .l-sidebar {
   width:200px;
   height:500px;
   position:absolute;
   top:0;
   left:0;
   background:blue;
}
.mainbar {
   margin-left:200px;
   height:500px;
   margin-right:300px;
   background:green;
}
.r-sidebar {
   width:300px;
  height:500px;
   position:absolute;
  top:0;
   right:0;
   background:blue;
}
 

0 0
原创粉丝点击