您的位置:首页 > Web前端 > CSS

css布局左右定宽,中间自适应

2016-12-05 20:44 375 查看

一、基于传统的position或者浮动,让其脱离文档流的方法

1、position(绝对定位法)

绝对定位法原理是将左右两边使用absolute定位,因为绝对定位使其脱离文档流,后面的center会自然流动到他们上面,然后使用margin属性,留出左右元素的宽度,既可以使中间元素自适应屏幕宽度。

代码如下:

<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<style type="text/css">
*{
margin: 0;
padding: 0;
}
.left,.right{
position: absolute;
width: 200px;
height: 200px;
background-color: #df8793;
top:0;
}
.left{
left:0px;
}
.right{
right: 0px;
}
.center{
margin: 0 210px;
overflow: hidden;
background-color: yellow;
height: 200px;
}
</style>
<body>
<div class='left'>left</div>

<div class='right'>right</div>
<div class='center'>center
</div>
</body>
</html>


2.使用float:自身浮动法

自身浮动法的原理就是使用对左右使用分别使用float:left和float:right,float使左右两个元素脱离文档流,中间元素正常在正常文档流中,使用margin指定左右外边距对其进行一个定位。

代码如下:

<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<style type="text/css">
*{
margin: 0;
padding: 0;
}
.left,.right{
width: 200px;
height: 200px;
background-color: #df8793;
}
.left{
float: left;
}
.right{
float: right;
}
.center{
margin: 0 210px;
overflow: hidden;
background-color: yellow;
height: 200px;
}
</style>
<body>
<div class='left'>left</div&g
4000
t;

<div class='right'>right</div>
<div class='center'>center
</div>
</body>
</html>


注意:此种方法center的div需要放在最后面


3.圣杯布局

圣杯布局的原理是margin负值法。使用圣杯布局首先需要在center元素外部包含一个div,包含div需要设置float属性使其形成一个BFC,并设置宽度,并且这个宽度要和left块的margin负值进行配合,具体原理参考这里。这里对圣杯布局解释特别详细。

<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<style type="text/css">
*{
margin: 0;
padding: 0;
}
.wrap{
width: 100%;
float: left;
height: 200px;
background-color: #238978;
}
.center{
margin: 0 210px;
}
.left{
float: left;
margin-left: -100%;
width: 200px;
height: 200px;
background-color: #eee;
}
.right{
float: left;
margin-left: -200px;
width: 200px;
height: 200px;
background-color: #eee;
}
</style>
<body>
<div class='wrap'>
<div class='center'>center</div>
</div>
<div class='left'>left</div>
<div class='right'>right</div>
</body>
</html>


二、css3新特性:弹性盒子

在外围包裹一层div,设置为display:flex;中间设置flex:1;但是盒模型默认紧紧挨着,可以使用margin控制外边距。(关于弹性盒子的特点,之前在博客里总结过,如果不是很清晰,可以一看)

代码如下:

<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<style type="text/css">
*{
margin: 0;
padding: 0;
}
.wrap{
display: flex;
}
.center{
flex:1;
margin: 0 10px;
background-color: pink;
}
.left{
width: 200px;
height: 200px;
background-color: #eee;
}
.right{
width: 200px;
height: 200px;
background-color: #eee;
}
</style>
<body>
<div class='wrap'>
<div class='left'>left</div>
<div class='center'>center</div>
<div class='right'>right</div>
</div>

</body>
</html>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  css 布局
相关文章推荐