保证金顶部不适用于某些元素

时间:2013-05-22 06:06:35

标签: html css html5 css3 layout

我有2个不响应margin: 260px 0 0 0;margin-top: 260px;的元素。我不知道为什么。当我在IE中打开dev工具并检查元素时,边距就在那里,但是元素仍然位于div的顶部,就好像margin: 260px 0 0 0;没有设置一样。

为什么保证金不适用于a.SideContainer a {...}内的.RightSide a {...}元素?

        <section class="RightSide SideContainer">
            <a href="~/Shared/Services/WebDevelopment">Packages &amp; Pricing</a>
        </section>


    .SideContainer h1 {
        color: white;
    }

    .SideContainer a {
        margin: 260px 0 0 0;
    padding: 10px 15px 10px 15px;
    background-color: #ec462f;
    color: white;
    }

.RightSide {
    float: right;
}

    .RightSide a {
        margin-top: 200px;
    }

6 个答案:

答案 0 :(得分:3)

锚标记是inline元素,因此顶部和底部边距样式不会按预期应用于它们。将display属性设置为inline-block,它应该可以正常工作。

.SideContainer a, .RightSide a {
    display: inline-block;
}

请记住,将元素的display属性设置为inline-block将导致源代码中的空格被渲染。 Here's如何防止这种情况。

另一种方法是将display属性设置为block,并在需要时设置float属性。

.SideContainer a, .RightSide a {
    display: block;
    float: left; /*if required*/
}

答案 1 :(得分:0)

它不起作用,因为您的锚标记是内联元素,并且不响应边距。

如果您在.SideContainer a上的CSS中添加display:block,它就会移动。

http://codepen.io/anon/pen/Girwh

答案 2 :(得分:0)

内联元素不会对保证金做出回应。

你需要制作一个标签显示块,或者你可以将它浮动到右边,这样它就像普通的“a”标签一样正常,并且也会响应边距。

试试这个:

.RightSide a {
    margin-top: 200px;
    float: right;
}

答案 3 :(得分:0)

我处理了您的代码,您必须将display:inline-blcok放在锚标记中才能获得margin-top

解决方案:

<!DOCTYPE HTML>
<html>
    <head>
        <title></title>
        <style type="text/css">
            .SideContainer h1 {
                color:white;
            }
            .SideContainer a {
                padding:10px 15px 10px 15px;
                background-color:#ec462f;
                color:white;
            }
            .RightSide {
                float:right;
            }
            .RightSide a {
                display:inline-block;
                margin-top:200px;
            }
        </style>
    </head>
    <body>
        <section class="RightSide SideContainer">
            <a href="~/Shared/Services/WebDevelopment">Packages &amp; Pricing</a>
        </section>
    </body>
</html>

答案 4 :(得分:0)

我认为添加display:block

就足够了
.RightSide {
margin-top: 200px;
display: block;
}

答案 5 :(得分:0)

你需要像你这样漂浮'a'标签:

.SideContainer a {
    ...
    float:left;
}