2

div1 is floated left so div2 comes up beside it. If I want to add a 10px left margin on div2, why do I need to set it to 60px? ie. the width of div1 + 10px. Can I make div2 relative to div1 so I can set the div2 left margin to 10px?

<!DOCTYPE html>
<html>
    <head>
        <style>
            #div1{
                width: 50px;
                float: left;
            }
            #div2 {
                margin-left: 60px;
            }
            #div1, #div2{
                border: 1px solid red;
            }
        </style>
    </HEAD>
    <BODY>
        <div>
            <div id="div1">
                div1
            </div>
            <div id="div2">
                div2
            </div>
        </div>
    </BODY>
</html>

JSfiddle

4

2 に答える 2

2

Floats break the element out of the document flow. The reason you need to add the left margin at 60px is to have it clear the left floated div... if you want them both inline, I'd suggest using:

        #div1{
            width: 50px;
            display: inline-block;
        }
        #div2 {
            margin-left: 10px;
            display: inline-block;
        }
        #div1, #div2{
            border: 1px solid red;
        }
于 2013-10-11T15:17:23.107 に答える
0

float: left#div2を追加する必要があります。

于 2013-10-11T15:21:43.487 に答える