常见布局:左栏固定右栏自适应

这节我们要实现的目的只有一个,就是一栏固定一栏自适应。

1、使用div,这样就可以自动填满父标签宽度,设想方案如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>demo</title>
    <style>
    body{padding: 0;margin:0;}
        #wrap{
            overflow: hidden;*zoom: 1;
        }        
        #sitebar{background: #D7B9FF; float: left; width: 300px;}
        #content{
            background: #36CEC5;margin-left:300px;
        }
    </style>
</head>
<body>
    <div id="wrap">    
         <div id="sitebar">我是固定左栏</div>    
        <div id="content">
            我是右栏内容
        </div> 
    </div>
</body>
</html>

但这个有个限制,就是sidebar必须在content之前!

2、遵循网页优化的角度,主要内容应该放前面,那么需要把content和sitebar位置换一下,然后固定栏使用绝对定位

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>demo</title>
    <style>
    body{padding: 0;margin:0;}
        #wrap{
            *zoom: 1; position: relative;
        }        
        #sitebar{background: #D7B9FF; width: 300px;position: absolute;left:0;top: 0;}
        #content{
            background: #36CEC5;margin-left: 300px;
        }
    </style>
</head>
<body>
    <div id="wrap">    
        <div id="content">
            我是右栏内容
        </div> 
         <div id="sitebar">我是固定左栏</div>    
    
    </div>

</body>
</html>

 但是这样也有一个问题,因为左栏使用了绝对定位,那么再有其他层的话就会被它挡住。

3、加多一个层,使用浮动和margin结合

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>demo</title>
    <style>
    body{padding: 0;margin:0;}
         
        #sitebar{background: #D7B9FF; width: 300px;float: left;}
        #content{
            background: #36CEC5;float: right;width: 100%;margin-right: -300px;
        }
            #content_wrap{
                margin-right: 300px;
            }
    </style>
</head>
<body>
    <div id="wrap">    
       <div id="content_wrap">
            <div id="content">
            我是内容
        </div> 
         <div id="sitebar">我是固定左栏</div>    
       </div>

    </div>
    
</body>

总结该布局应具备条件:

1、content自适应,sidebar固定

2、content在sidebar之前

3、后面的元素不受影响

若想左栏为100%,可参考以下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>demo</title>
    <style>
    body{padding: 0;margin:0;}
    body,html{width: 100%;height: 100%;}
        #wrap{height: 100%;}
        #sitebar{background: #D7B9FF; width: 300px;float: left;height: 100%;}
        #content{
            background: #36CEC5;float: right;width: 100%;margin-right: -300px;
        }
            #content_wrap{
                margin-right: 300px;height: 100%;
            }
    </style>
</head>
<body>
    <div id="wrap">    
       <div id="content_wrap">
            <div id="content">
            Underscore 是一个 JavaScript 工具库,它提供了一整套函数式编程的实用功能,但是没有扩展任何 JavaScript 内置对象。 他解决了这个问题:“如果我面对一个空白的 HTML 页面,并希望立即开始工作,我需要什么?” 他弥补了 jQuery 没有实现的功能,同时又是 Backbone 必不可少的部分。
        </div> 
         <div id="sitebar">我是固定左栏</div>    
       </div>

    </div>    
</body>

原文地址:https://www.cnblogs.com/tinyphp/p/5560422.html