本篇文章给大家介绍的内容是关于利用CSS的float属性实现二级响应式页面,内容很详细,有一定的参考价值。
话不多说,直接来看正文~
我们使用float:left属性来实现二级响应式页面(推荐课程:CSS视频教程)
代码如下:
LRColumnSimple.html
LRColumnSimple.cssbody {
background-color:#C0C0C0;
}
.Container {
background-color:#FFFFFF;
width:760px;
margin-left:auto;
margin-right:auto;
}
.LeftColumn {
float:left;
width:360px;
}
.RightColumn {
float:left;
width:360px;
}
.EndColumn {
clear:left;
}
在浏览器上的效果如下:
补充:将图像在显示在框架中间
在框架的中间显示图像的话,需要设置为图像设置text-align:center。
代码如下:
LRColumnSimpleImageCenter.html
效果如下:图像在中间显示
在页面上的响应式显示
LRColumnSimpleResponsiveW1.html
LRColumnSimpleResponsiveW1.cssbody {
background-color:#C0C0C0;
}
.Container {
background-color:#FFFFFF;
width:70%;
margin-left:auto;
margin-right:auto;
}
.LeftColumn {
float:left;
width:360px;
}
.RightColumn {
float:left;
width:360px;
}
.EndColumn {
clear:left;
}
效果如下:
如果您在此处缩小宽度,它将会变为如下图所示。它用浮动左对齐,但由于宽度变窄,它变成一个包裹的显示。此时,当图像在右边界上时,图像的说明文本显示在图像上,左边的说明文本显示在图像的底部。
响应的例子:
在先前的HTML中,存在如下问题:当窗口宽度变窄并且框架被折叠时,说明文字的位置不能成为同一位置的问题。我来介绍避免这种现象的代码。
LRColumnSimpleResponsiveW2.html
LRColumnSimpleResponsiveW2.cssbody {
background-color:#C0C0C0;
}
.Container {
background-color:#FFFFFF;
width:70%;
margin-left:auto;
margin-right:auto;
}
.TextColumnA {
float:left;
width:360px;
}
.ImageColumnA {
float:left;
width:360px;
text-align:center;
margin-left:auto;
margin-right:auto;
}
.TextColumnB {
float:right;
width:360px;
}
.ImageColumnB {
float:right;
width:360px;
text-align:center;
margin-left:auto;
margin-right:auto;
}
.EndColumn {
clear:both;
}
说明:
TextColumnA和ImageColumnA类用于左侧的描述性文本,而框架用于显示右侧的图像。对于这些类,指定了float:left,并且前面描述的描述性语句位于左侧,图像位于右侧。另一方面,TextColumnB和ImageColumnB类用于右侧的描述性文本,而框架用于显示左侧的图像。在这些类中,指定了float:right,因此前面描述的描述性文本将放在右侧,图像将放在左侧。
当窗口宽度变窄时,先前描述的框架首先显示在float:left的框架中。即使在指定了float:right的帧中,也会首先执行前面描述的描述性语句的放置,因此描述框架的文字将显示在图像上方。
效果如下:
减小窗口的宽度。框架将折叠,但描述文字将在图像上均匀显示。
下面我们来看一个基于前面代码的实际例子
LRColumnSimpleResponsive.html
LRColumnSimpleResponsive.cssbody {
background-color:#C0C0C0;
}
.Container {
background-color:#FFFFFF;
width:760px;
margin-left:auto;
margin-right:auto;
}
.TextColumnA {
float:left;
width:360px;
}
.ImageColumnA {
float:left;
width:360px;
text-align:center;
margin-left:auto;
margin-right:auto;
}
.ImageColumnA img{
width:200px;
}
.TextColumnB {
float:right;
width:360px;
}
.ImageColumnB {
float:right;
width:360px;
text-align:center;
margin-left:auto;
margin-right:auto;
}
.ImageColumnB img{
width:200px;
}
.EndColumn {
clear:both;
}
@media screen and (max-width: 760px) {
.Container {
width:95%;
}
.TextColumnA {
float:none;
width:100%;
}
.ImageColumnA {
float:none;
width:100%;
text-align:center;
margin-left:auto;
margin-right:auto;
}
.ImageColumnA img{
width:80%;
}
.TextColumnB {
width:100%;
}
.ImageColumnB {
width:100%;
text-align:center;
margin-left:auto;
margin-right:auto;
}
.ImageColumnB img{
width:80%;
}
}
说明:
它与前面的代码相同,但如果使用CSS媒体查询并且Web浏览器的宽度为760像素或更小,则将float设置为none并取消该列。此外,图像显示的屏幕宽度为80%。它由此在一列中显示。
效果如下:
如果窗口的宽度是760像素或更多,则它显示在两列中。
当窗口的宽度变为760像素或更小时,它变为一列。图像的宽度也是横向宽度的80%。