css如何实现两栏布局,左边固定宽度,右边宽度自适应,且高度和浏览器当前高度一致

无论浏览器宽度怎么改变,都保证左边这个div宽度固定为300px,右边宽度随浏览器宽度自适应,且两个div的高度和浏览器当前高度一致

阅读 7.9k
6 个回答
#left {
    position: fixed;
    left: 0;
    top: 0;
    height: 100vh;
    width: 300px;
    /* background: blue; *//* 解开此处注释来查看效果 */
}

#right {
    position: fixed;
    left: 300px;
    top: 0;
    height: 100vh;
    width: calc(100vw - 300px); 
    /* 如果浏览器不支持CSS3 calc方法,可以使用js计算宽度 */
    /* background: red; *//* 解开此处注释来查看效果 */
}

我的内心是崩溃的,不知道为什么jsbin显示不了,不太会用。

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
  <div class="test">你好世界</div>
  <div class="test2">你好世界</div>
</body>
</html>
.test{
  position: absolute;
  background: black;  
  color: white;
  width: 300px;
  bottom: 0px;
  top: 0px;
  
}

.test2{
  position: absolute;
  background: purple;
  color: white;
  right: 0;
  left: 300px;
  top: 0;
  bottom: 0;
}

clipboard.png

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<style> 
body{
    margin:0;
    padding:0;
    height:100%;
}
.left{
    width:300px;
    height:100%;
    background-color:red;
    float: left;
}
.right{
    height:100%;
    float: left;
    background-color:yellow;
}
.box{
    position: absolute;
    height:100%;
    width:100%
}
</style>
<body>
   <div class="box">
       <div class="left">111</div>
       <div class="right">11111</div>
   </div>
</body>
</html> 

这样的话右边宽度会随内容填充来适应,如果可以的话可以考虑用Js控制下

看了以上几种方法似乎都解决不了啊,或者说是纯CSS方法不行,在有的浏览器下calc(100vw-300px)没有用。我只能用js来替换这一条了,right.style .width = (document.document.clientWidth - 300)+ "px";
希望对你有用!

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>demo</title>
    <style type="text/css">
        * {
            margin: 0;
            padding: 0;
        }
        html, body {
            height: 100%;
        }
        .layout {
            height: 100%;
        }
        .layout:before,
        .layout:after {
            content: ' ';
            display: table;
        }
        .layout:after {
            clear: both;
        }
        .layout .left {
            width: 300px;
            height: 100%;
            float: left;
            background-color: #000;
        }
        .layout .right {
            height: 100%;
            overflow: hidden;
            background-color: #ff0000;
        }
    </style>
</head>
<body>
    <div class="layout">
        <div class="left"></div>
        <div class="right"></div>
    </div>
</body>
</html>

利用了BFC

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题