最近要对网站进行调整,将网页布局从原先的定宽改成宽度自适应,这里总结遇到的几个案例
案例一:设置宽度百分比,让网页中的两栏都按百分比来做宽度调整
注:css中的background-color:red;height:200px,主要是为了方便展示,在网页中显示为一个色块,跟宽度自适应无关
<div style="background-color:red;height:200px;float:left;width:20%"></div>
<div style="background-color:blue;height:200px;float:right;width:80%;"></div>
-->按比例缩小
这种情况下,如果窗口宽度是1000px,则左右两栏分别是200px和800px,如果宽度是500px,左右两栏也会按比例缩成100px、400px。
案例二、左边栏是定宽;右边栏宽度自适应,填充左边栏剩下的宽度
<div style="background-color:red;height:200px;float:left;width:200px"></div>
<div style="background-color:blue;height:200px;margin-left:200px"></div>
-->缩小时,左边宽度不变
原理:设置左边栏宽度,同时让右边栏的左边距和左边栏保持一致
案例三、左边栏定宽,当窗口宽度小于某个值时,重新调整左边栏定宽
<html>
<head>
<style type="text/css">
.left{
width:400px;
}
.right{
margin-left:400px
}
@media screen and (max-width:600px){
.left{
width:200px;
}
.right{
margin-left:200px
}
}
</style>
</head>
<body>
<div class="left" style="background-color:red;height:200px;float:left"></div>
<div class="right" style="background-color:blue;height:200px"></div>
</html>
-->当窗口变小,小于600px时,左边栏变小为200px
原理:
这个效果,是css样式中的@media screen and (max-width:600px)所起的作用。当窗口宽度小于600px时,会使用该行括号内的另一套样式。
使用场景:当窗口宽度比较大时,能让各边栏都保持较大的宽度,窗口特别小时,又能保证指定区域不要小于指定值,防止该区域中的文本被截断或换行(例如本例中的左边栏)