V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
Dive into HTML5
http://diveintohtml5.org/
CareiOS
V2EX  ›  HTML

使用 css 单独文件与写在 style 里为何效果不一样?

  •  
  •   CareiOS · 2016-07-07 10:19:35 +08:00 · 4694 次点击
    这是一个创建于 2848 天前的主题,其中的信息可能已经有所发展或是发生改变。

    初学 html5 写网页,想写一个 V2EX 这样的布局,如果用单独的 css 文件来布局就可以,如果写在 div 的 style 中, div 就会换行。这两种写法效果应该一样的呀。

    a.css 内容:

    .mcenter{margin:0 410px 0 210px; background:#ffe6b8; height:600px;}
    .mright{width:400px; margin-bottom:-3000px; padding-bottom:3000px; background:#f0f3f9; float:right;}
    

    html 为:

    <!DOCTYPE html>
    <html>
    <head>
       <title>布局实例</title>
       <link rel="stylesheet" href="a.css" media="all">
       <meta charset="utf-8"/>
    </head>
    <body>
    
       <div class="mright">右边,无高度属性,自适应于最高一栏的高度</div>
       <div class="mcenter">中间,高度 600 像素,左右两栏的高度与之自适应</div>
    
       <div>
       <div id="center" style="margin:0 410px 0 210px; background:#ffe6b8; height:600px;"></div>
       <div id="sill" style="width:400px; margin-bottom:-3000px; padding-bottom:3000px; background:#f0f3f9; float:right;"></div>
       </div>
    </body>
    </html>
    
    第 1 条附言  ·  2016-07-07 15:06:21 +08:00
    找到一篇好文章,介绍 float 的: http://www.cnblogs.com/iyangyuan/archive/2013/03/27/2983813.html
    4 条回复    2016-07-07 14:12:18 +08:00
    lonelinsky
        1
    lonelinsky  
       2016-07-07 10:32:16 +08:00
    因为你把 sill 和 center 的顺序写反了呀,你调整下先后顺序再看看
    SpicyCat
        2
    SpicyCat  
       2016-07-07 10:40:22 +08:00
    把 right div 放到 center div 上面
    这样:

    <div id="sill" style="width:400px; margin-bottom:-3000px; padding-bottom:3000px; background:#f0f3f9; float:right;">sill</div>
    <div id="center" style="margin:0 410px 0 210px; background:#ffe6b8; height:600px;">center</div>
    CareiOS
        3
    CareiOS  
    OP
       2016-07-07 12:27:40 +08:00
    @SpicyCat
    @lonelinsky
    顺序是, float 在哪边就要先放那边是吗?
    lonelinsky
        4
    lonelinsky  
       2016-07-07 14:12:18 +08:00   ❤️ 1
    @CareiOS 非前端工程师,我的理解是这样的:
    一个 div 如果没有设置 float 属性的时候,默认的 display 是 block ,会独占一行,所以写在后面的换行了。
    而一旦设置了 float 属性,则会根据设置的方向,占用一部分,这个时候行面的元素如果可以在空出来的部分摆放下的会,就会占用空出来的部分,而不是直接占用下一行。

    简单点说, float 属性不光影响了自己的位置,同时也影响了跟在其后面的元素的布局方式。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3329 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 11:45 · PVG 19:45 · LAX 04:45 · JFK 07:45
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.