使用css进行布局,我们都知道浮动,那么我们为什么要使用浮动呢?下面我们就以京东登录界面顶部的布局来讨论这个问题。下图是我们写好的京东登录界面。
在顶部布局中,代码如下
html代码
<header>
<div class="header-content">
<a href="index.html" class="logo"></a>
<span>欢迎登录</span>
<div class="login"><i></i><a href="#">登录页面,调查问卷</a> </div>
</div>
</header>
css代码
公共样式index.css
html,body,header,main,nav,aside,article,summary,details,footer,p,img,ul,li,ol,dl,dd,dt,
h1,h2,h3,h4,h5,section{
margin:0;
padding:0;
}
html,body{
width:100%;
font-family: "Microsoft YaHei","Hiragino Sans GB";
color: #666;
}
ul,ol,li{
list-style: none;
}
a{
text-decoration: none;
}
h3{font-weight: normal}
登录界面样式login.css
*{
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
/*标准盒子模型*/
box-sizing: border-box;
}
header{
width:100%;
height: 80px;
}
header .header-content{
box-sizing: border-box;
width: 990px;
height: 80px;
margin: 0 auto;
vertical-align: middle;
/*background-color: red;*/
}
header .header-content .logo{
float: left;
width: 160px;
height: 60px;
/*左,上*/
background: url("../image/icon.png") no-repeat 0 15px;
}
header .header-content span{
float: left;
font-size: 24px;
padding-left: 30px;
padding-top: 20px;
}
header .header-content .login{
float: right;
font-size: 12px;
margin-top: 55px;
padding-bottom: 5px;
font-family: Arial,Verdana,"\5b8b\4f53";
}
header .header-content .login i{
display: inline-block;
width: 18px;
height: 16px;
margin: 0 5px;
background: url("../image/msg-icon.png") no-repeat ;
}
header .header-content .login a{
color: #999;
position: relative;
top: -5px;
}
header .header-content .login a:hover {
color: #E4393C;
text-decoration: underline;
}
由上述代码,我们可以看到在对顶部的左侧“京东图标”,“欢迎登录”设置左浮动,对右侧的“登录页面,调查问卷”设置右浮动。那么如果我们不设置浮动会有什么效果呢?
当我们把header .header-content .logo 和 header .header-content span的左浮动关掉,此时顶部左侧显示的效果为:
此时我们可以看到出现2个问题
1.京东的图标不见了
2.“欢迎登录”跑到左边了
京东图标是通过标签a显示的。a是行内元素,在文档流中的时候因为是行内元素所以无法设置宽高;而当设置了绝对定位或者浮动,会生成块框(即变成块元素),所以就可以设置宽高了。这里把行内元素a的浮动关闭,会导致a标签设置的宽和高是无效的,所以京东的图标就不会显示。
“欢迎登陆”是通过span标签显示的,span也是行内元素。行内元素会在一条直线上,是在同一行的。当显示京东图标的a标签消失,此时span的左浮动也关闭,所以span就会按照行内元素的默认状态,显示在一行的最左侧。
使用浮动可以是行内元素变为块级元素,浮动是一把双刃剑,我们要注意一点,能不使用浮动,则不要使用浮动。