CSS两栏布局(四种方法)
2020-02-12 本文已影响0人
凯凯frank
两栏布局,要求左边固定,右边自适应。
方法1------浮动
思路:左边容器左浮动,宽度固定,右边元素设置margin-left
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
*{ margin: 0; padding: 0; box-sizing: border-box; }
html,body{ height: 100%; }
.left-panel{
float: left;
width: 200px;
height: 100%;
background-color: red;
}
.main-panel{
height: 100%;
margin-left: 200px;
background-color: #00a2ea;
border-left: 1px solid #000;
}
</style>
</head>
<body>
<div class="left-panel">left</div>
<div class="main-panel">main</div>
</body>
</html>
方法2------绝对定位
思路:左边容器绝对定位,宽度固定,右边元素设置margin-left
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
*{ margin: 0; padding: 0; box-sizing: border-box; }
html,body{ height: 100%; }
.left-panel{
position: absolute;
left: 0;
top: 0;
width: 200px;
height: 100%;
background-color: red;
}
.main-panel{
height: 100%;
margin-left: 200px;
background-color: #00a2ea;
border-left: 1px solid #000;
}
</style>
</head>
<body>
<div class="left-panel">left</div>
<div class="main-panel">main</div>
</body>
</html>
方法3------绝对定位
思路:左边宽度固定,右边元素绝对定位,设置left,设置宽度为剩下容器的宽度(width可以使用calc计算,也可以同时设置left和right,让他自行拉伸,不用指定width)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
*{ margin: 0; padding: 0; box-sizing: border-box; }
html,body{ height: 100%; }
.left-panel{
width: 200px;
height: 100%;
background-color: red;
}
.main-panel{
position: absolute;
left: 200px;
top: 0 ;
right: 0;
/*width: calc(100% - 200px);*/
height: 100%;
background-color: #00a2ea;
border-left: 1px solid #000;
}
</style>
</head>
<body>
<div class="left-panel">left</div>
<div class="main-panel">main</div>
</body>
</html>
方法4:flex布局
思路:父元素flex布局,默认方向就是水平排列。左边的子元素宽度固定,右边的子元素设置flex-grow:1;自动填充容器剩余宽度。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
*{ margin: 0; padding: 0; box-sizing: border-box; }
html,body{ height: 100%; }
.container{
display: flex;
height: 100%;
}
.left-panel{
width: 200px;
background-color: red;
}
.main-panel{
flex-grow: 1;
background-color: #00a2ea;
border-left: 1px solid #000;
}
</style>
</head>
<body>
<div class="container">
<div class="left-panel">left</div>
<div class="main-panel">main</div>
</div>
</body>
</html>