V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
shpasspass
V2EX  ›  问与答

一个简单的css,缺困扰了我很久,求大家帮忙解释一下

  •  
  •   shpasspass · Mar 31, 2013 · 3161 views
    This topic created in 4787 days ago, the information mentioned may be changed or developed.
    css的代码是这个
    .a{
    width:950px;
    height:500px;
    background:#aabbcc;
    }

    .b{
    width:240px;
    height:200px;
    background:#ff0000;
    margin-left:15px;
    margin-top:125px;
    }
    html的代码是这个
    <div class="a">
    <div class="b"></div>
    </div>


    问题是,用了margin-left后,b盒子距离a盒子左侧有5px的外边距
    但是用了margin-top后,2个盒子都同时向上出现125px的外边据,这是为什么呢?
    我的问题是,为什么上边距加上去后,对ab2个盒子都产生了作用,而只加左边距,那么就只对b盒子产生了作用。
    5 replies    1970-01-01 08:00:00 +08:00
    best1a
        1
    best1a  
       Mar 31, 2013   ❤️ 1
    zetttt
        2
    zetttt  
       Mar 31, 2013   ❤️ 1
    就是简单的浮动问题
    给.a 加个 float:left 就好了
    shpasspass
        3
    shpasspass  
    OP
       Mar 31, 2013
    @best1a 原来还有这么一说。hoho
    shpasspass
        4
    shpasspass  
    OP
       Mar 31, 2013
    @zetttt 原来还可以这样,hoho
    emric
        5
    emric  
       Mar 31, 2013   ❤️ 1
    LS说对了,这个属于边距重叠的问题.
    给父元素设置overflow:hidden,就OK/
    还有几种方法:
    http://www.benben.cc/blog/?p=98
    参考&文档:
    http://www.w3.org/TR/CSS21/box.html#collapsing-margins
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   3505 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 40ms · UTC 10:39 · PVG 18:39 · LAX 03:39 · JFK 06:39
    ♥ Do have faith in what you're doing.