调整容器div内的div的上边距将内部div和容器div都从主体向下推 [英] Adjusting the margin-top of a div inside of a container div pushes both the inner div and container div down from body

查看:176
本文介绍了调整容器div内的div的上边距将内部div和容器div都从主体向下推的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我觉得这一定是我做一些愚蠢的事情的问题,但我无法弄清楚. 这是一个演示我的问题的演示页面.该页面的来源:

I feel like this must be an issue of me doing something silly, but I can't figure it out. Here's a demo page showing my problem. The source of the page:

<html>
<head>
    <title>demo</title>
    <style type='text/css'>
        body{
            margin: 0px;
            padding: 0px;
        }
        #container{
            height: 100%;
            background-color: black;
        }
        #logo{
            margin: 25px auto auto auto;
            width: 360px;
            height: 45px;
            background-color: goldenrod;
        }
    </style>
</head>
<body>
    <div id='container'>
        <div id='logo'>
            <p>logotext.</p>
        </div>
    </div>
</body>
</html>

因此,您对边距的上限值进行的调整越多,#logo和#container都将在页面中越拖越深. #container应该保持原状,而#logo应该向下移动页面.

So the more you adjust the top value of margin, the further down the page both #logo and #container get dragged. #container should stay put and #logo should be shifting down the page.

推荐答案

这是由页边距缩小引起的.如果两个元素的边距相等,则这些边距将合并.在此处,有很好的解释.转到Collapsing Margins Between Parent and Child Elements部分.

This is caused by collapsing margins. If two elements have touching margins, then the margins merge. There is a great explanation of this here. Go to the section called Collapsing Margins Between Parent and Child Elements.

这是三种不同的解决方案.

Here are three different solutions.

一种是将overflow: auto添加到容器中.这将更改BCF(块格式设置上下文). 此处更详细地描述.

One is to add overflow: auto to the container. This changes the BCF (Block Formatting Context). This technique is described in more detail here.

#container {
    height: 100%;
    background-color: black;
    /* Add oveflow auto to container */
    overflow: auto;
}

http://jsfiddle.net/bzVgV/20/

第二个方法是在容器上使用填充而不是徽标上的空白.这样就消除了边距.

A second is to use padding on the container instead of a margin on logo. This takes margins out of the equation.

#container {
    height: 100%;
    background-color: black;
    /* Use padding on container instead of margin on logo */
    padding-top: 30px;
}

http://jsfiddle.net/bzVgV/18/

最后的解决方案是使页边距不再碰触.您可以通过向父级添加1px填充来实现此目的.

A final solution is to make the margins no longer touch. You can do this by adding a 1px padding to the parent.

#container {
    height: 100%;
    background-color: black;
    /* Now margins of container and logo won't touch */
    padding-top: 1px;
}

http://jsfiddle.net/bzVgV/21/

这篇关于调整容器div内的div的上边距将内部div和容器div都从主体向下推的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆