css中为什么需要浮动?

使用css进行布局,我们都知道浮动,那么我们为什么要使用浮动呢?下面我们就以京东登录界面顶部的布局来讨论这个问题。下图是我们写好的京东登录界面。


在顶部布局中,代码如下

html代码

 

<header>
    <div class="header-content">
        <href="index.html" class="logo"></a>
        <span>欢迎登录</span>
        <div class="login"><i></i><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-stylenone;
}
a{
    text-decorationnone;
}
h3{font-weightnormal}

 

登录界面样式login.css

*{
    -webkit-box-sizingborder-box;
    -moz-box-sizingborder-box;
    /*标准盒子模型*/
    box-sizing
border-box;
}
header{
    width:100%;
    height80px;
}
header .header-content{
    box-sizingborder-box;
    width990px;
    height80px;
    marginauto;
    vertical-alignmiddle;
    /*background-color: red;*/
}
header .header-content .logo{


    floatleft;
    width
160px;
    height60px;
    /*左,上*/
    background
url("../image/icon.png"no-repeat 0 15px;
}
header .header-content span{
    float
left;
    font-size24px;
    padding-left30px;
    padding-top20px;
}
header .header-content .login{
    floatright;
    font-size12px;
    margin-top55px;
    padding-bottom5px;
    font-familyArial,Verdana,"\5b8b\4f53";
}
header .header-content .login i{
    displayinline-block;
    width18px;
    height16px;
    margin0 5px;
    backgroundurl("../image/msg-icon.png"no-repeat ;
}
header .header-content .login a{
    color#999;
    positionrelative;
    top: -5px;

}
header .header-content .login a:hover {
    color#E4393C;
    text-decorationunderline;
}

 

由上述代码,我们可以看到在对顶部的左侧“京东图标”,“欢迎登录”设置左浮动,对右侧的“登录页面,调查问卷”设置右浮动。那么如果我们不设置浮动会有什么效果呢?

当我们把header .header-content .logo  header .header-content span的左浮动关掉,此时顶部左侧显示的效果为:

 

此时我们可以看到出现2个问题

1.京东的图标不见了

2.“欢迎登录”跑到左边了

 

京东图标是通过标签a显示的。a是行内元素,在文档流中的时候因为是行内元素所以无法设置宽高;而当设置了绝对定位或者浮动,会生成块框(即变成块元素),所以就可以设置宽高了。这里把行内元素a的浮动关闭,会导致a标签设置的宽和高是无效的,所以京东的图标就不会显示。

欢迎登陆是通过span标签显示的,span也是行内元素。行内元素会一条直线上,是在同一行的。当显示京东图标的a标签消失,此时span的左浮动也关闭,所以span就会按照行内元素的默认状态,显示在一行的最左侧。

使用浮动可以是行内元素变为块级元素,浮动是一把双刃剑,我们要注意一点,能不使用浮动,则不要使用浮动。

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值