三种方法实现CSS三栏布局

100人浏览   2024-08-20 08:33:10


本文会分别介绍三种CSS实现三栏布局的方法,可在浏览器中打开查看效果

1.方法一:自身浮动的方法

实现方法:需要左栏向左浮动,右栏向右浮动,中间设左右margin来撑开距离

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <title>CSS实现三栏布局1</title>
 <style type="text/css">
 body{
 margin: 0;
 padding: 0;
 }
 .left{
 width:200px;
 height: 300px;
 background-color: #DC698A;

 float:left;

 }
 .middle{
 /*width:100%;*/
 /*中间栏不要设宽度,包括100%*/
 height: 300px;
 background-color: #8CB08B;

 margin:0 200px;
 }
 .right{
 width: 200px;
 height: 300px;
 background-color: #3EACDD;

 float: right;
 }
 </style>
</head>
<body>
 <!-- 左栏左浮右栏右浮,中间不设宽度用左右margin值撑开距离,且布局中中间栏放最后 -->
 <!-- 中间栏实际宽度是当前屏的100% -->
 <div class="left">左栏</div>
 <div class="right">右栏</div>
 <div class="middle">中间栏</div>
</body>
</html>

注意:该方法在html布局时,要把中间栏放在左栏、右栏后面,左栏和右栏的顺序不定

实现的效果如下:

自身浮动实现三栏布局

2.方法二:margin负值法

实现方法:两边两栏宽度固定,中间栏宽度自适应,左栏、右栏、中间栏向左浮动,左栏的margin-left设为-100%,中间栏的width设为100%,右栏的margin-left设为-右栏宽度

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <title>CSS实现三栏布局2</title>
 <style type="text/css">
 body{
 margin:0;
 padding:0;
 }
 .left{
 width:200px;
 height: 300px;
 background-color: #DC698A;

 float:left;
 margin-left:-100%;
 }
 .middle{
 width:100%;
 height: 300px;
 background-color: #8CB08B;

 float:left;
 }
 .right{
 width:200px;
 height: 300px;
 background-color: #3EACDD;

 float: left;
 margin-left: -200px;
 }
 </style>
</head>
<body>
 <!-- 左栏中间栏右栏左浮,左栏margin-left:-100%,中间栏宽100%,,右栏margin-left:-右栏宽度 
 且布局上必须中间栏放第一个-->
 <div class="middle">中间栏</div>
 <div class="left">左栏</div>
 <div class="right">右栏</div>
</body>
</html>

注意:该方法在html布局时,要把中间栏放在第一个

此方法是实现圣杯布局和双飞翼布局的基础。

实现的效果如下:

margin负值法实现三栏布局

3.方法三:绝对定位法

实现方法:左栏、右栏绝对定位,分别固定到页面左右两侧,中间栏不设宽度,用左右margin来撑开距离

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <title>CSS实现三栏布局3</title>
 <style type="text/css">
 body{
 margin:0;
 padding: 0;
 }
 .left{
 width:200px;
 height: 300px;
 background-color: #DC698A;

 position: absolute;
 left:0;
 top:0;
 }
 .middle{
 /*width: 100%;*/
 height: 300px;
 background-color: #8CB08B;
 margin:0 200px;
 }
 .right{
 width:200px;
 height: 300px;
 background-color: #3EACDD;

 position: absolute;
 right:0;
 top:0;
 }
 </style>
</head>
<body>
 <!-- 左右两栏绝对定位,分别固定到页面的左右两侧,中间栏不设宽度,用左右margin撑开距离 -->
 <!-- 中间栏的实际宽度是当前屏的100% -->
 <div class="left">左栏</div>
 <div class="middle">中间栏</div>
 <div class="right">右栏</div>
</body>
</html>

实现的效果如下:


相关推荐