如何保证 div 在其他 div 内?

How to margin div inside other div?

html 主体,带有 table 和内部两个 div 的简单形式(登录和 table):

<body>
    <div id="container">
        <form>
            <div class="login">
                <div class="table">
                    <table class="userInput">
                        <tr>
                            <td><input type="text" placeholder="Username" id="username"
                                name="login"></td>
                        </tr>
                        <tr>
                            <td><input type="submit" value="submit"></td>
                        </tr>
                    </table>
                </div>
            </div>
        </form>
    </div>
</body>

我的css:

html,body {
    margin: 0;
    padding: 0;
    height: 100%;
}

table.userInput {
    margin-top: 15%;
    width: 100%;
    height: 100%;
}

div#container {
    background: pink;
    height: 100%;
}

div.login {
    background-color: black;
    margin-top: 15%;
    margin-left: auto;
    margin-right: auto;
    height: 10%;
    width: 10%;
    padding: 10px;
}

div.table {
    width: 100%;
    height: 100%;
    background-color: grey;
}

需要我的 div class="table"table class="userInput"margin-top:15% 之后以灰色背景可见,但在偏移后我可以看到登录 div class="login" 的黑色。如何用 margin-top 让它变成灰色?

margin-top: 15%;更改为padding-top: 15%;

table.userInput {
    padding-top: 15%;
    width: 100%;
    height: 100%;
}

根据你的图片,我认为这就是你想要的。

http://jsfiddle.net/7j8z3v3w/

如果我理解你的问题我建议你改变

padding:10px;

padding-top:10px;

并增加 <div class='login'> 元素的 宽度

编辑

你的形象几乎改变了一切,请检查这个fiddle: SOLUTION

我唯一改变的是删除 margin-top:15%; 并将其替换为 padding-top:15%; 这样我就可以将 background-color:grey; 添加到 table.userInput 元素。

在你的图片中看起来像。让我知道是否有帮助:)