Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Float and margin

Tags:

css

I need to know why the following code:

<!doctype html>
<html>
    <head>
        <title></title>
        <style type="text/css">
            *
            {
                margin:0px;
                padding:0px;
            }
            #right
            {
                float:right;
            }
            #content
            {
                margin-top:20px;
            }
        </style>
    </head>
    <body>
        <div id="right">a</div>
        <div id="content">b</div>
    </body>
</html>

Applies the 20px margin top also at the #right div.

like image 427
user232028 Avatar asked May 11 '26 20:05

user232028


2 Answers

Two things are missing: 1) clear:right; within #content. 2) widths need to be specified so that you are able to apply clear:right without the div's stacking.

<html>
    <head>
        <title></title>
        <style type="text/css">
            *
            {
                margin:0px;
                padding:0px;
            }
            #right
            {
                float:right;
                width:24%;
                border:1px solid red;
            }
            #content
            {
                margin-top:20px;
                width:74%;
                clear: right;
                border:1px solid aboue;
            }
        </style>
    </head>
    <body>
        <div id="right">a</div>
        <div id="content">b</div>
        <div style="clear:both;"></div>
    </body>
</html>

I've added the borders so it is easier to view.

like image 75
Jon Harding Avatar answered May 15 '26 16:05

Jon Harding


it doesn't, strictly. (the margin isn't applied to #right) floating takes the element out of the flow of the document.

add clear:right to #content

and floated elements ~should~ have a width.

like image 39
Ross Avatar answered May 15 '26 16:05

Ross



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!