首页 > 开发 > CSS > 正文

css中间自适应布局的5种解法详解

2024-07-11 08:33:21
字体:
来源:转载
供稿:网友

前言

在做页面时,我们往往会碰到页面布局相关的内容,面试时也经常会被问到,那么今天我就来总结一下关于页面布局的内容。

问题:如何实现三栏布局(高度固定,左中右的结构)

假设高度已知,请写出三栏布局,其中左右宽度均为300px,中间自适应。

看了上面的题目,有经验的人也许会觉得很简单,仔细想想,如果我们来写,能写出几种方案呢?一般都会想到两种吧,float和position定位,其实除了这两种外,还有3种可以写,下面我就来一一介绍一下:

方案一(float浮动)


<section class='layout float'>
<style>
.layout.float .left-right-center{
height: 100px;
}
.layout.float .left{
float: left;
width: 300px;
background-color: red;
}

.layout.float .right{
float: right;
width: 300px;
background-color: blue;
}

.layout.float .center{
background-color: yellow;
}
</style>
<article class="left-right-center">
<div class="left"></div>
<div class="right"></div>
<div class="center">我是中间的自适应元素--浮动</div>
</article>
</section>

原理:左右两个div由于浮动脱离了文档流,center就会上移,造成三栏布局的效果(前提是高度相同)
优点:兼容性高
缺点:需要清除浮动来防止影响其他元素
如果高度不固定,中间的内容会被撑开,左右两边不会一起撑开

方案二(绝对定位)


<section class="layout absolute">
<style>
.layout.absolute .left-center-right div{
position: absolute;
height: 100px;
}

.layout.absolute .left{
left: 0;
width: 300px;
background-color: red;
}

.layout.absolute .center{
left: 300px;
right: 300px;
background-color: yellow;
}

.layout.absolute .right{
right: 0;
width: 300px;
background-color: blue;
}
</style>
<article class="left-center-right">
<div class="left"></div>
<div class="center">
我是中间的自适应元素--绝对定位
</div>
<div class="right"></div>
</article>
</section>

原理:利用绝对定位以及宽度,将左右两边的div固定住,中间div的宽度就会有自适应的效果
优点:快捷
缺点:如果父元素脱离了文档流,子元素一定会脱离文档流,运用的场景不多
如果中间元素的高度增加,两边元素的高度不会增加,所以只有中间的div会撑开

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表