Why `float:left` doesn't work with a fixed width?

前端 未结 7 1198
谎友^
谎友^ 2021-01-02 06:39

I have two divs on a webpage and I would like both of them to have a fixed width and would like the first div to be floated to the left of the second div.

This sound

相关标签:
7条回答
  • 2021-01-02 06:53

    Float both divs left.

    Apply a positive left margin of width(div.right), in your case 200px.

    Apply a negative left margin of width(div.left) + width(div.right), in your case, 200px + 200px = 400px.

    div.left { float: left; width: 200px; margin-left: 200px; }
    div.right { float: left; width: 200px; margin-left: -400px; }
    
    0 讨论(0)
  • 2021-01-02 06:53

    You could add clear:both; your <p> tags. That would solve the problem. Without breaking the rest of the (example) page.

    0 讨论(0)
  • 2021-01-02 07:00

    It seems to me that it is the simple rule that blocks, unless floated, always start a new line. w3.org/TR/CSS2/visuren.html#block-formatting section 9.4.1 –

    0 讨论(0)
  • 2021-01-02 07:03

    in case you want both containers to float besides each other, you can rather use a span instead of a div. That might bring the problem to an end.

    0 讨论(0)
  • 2021-01-02 07:11

    The second element should be inline element.

    div.right {
        width: 200px;
        display: inline;
    }
    

    If you do not want to make second element inline, just float it to the left too. But your container will collapse. You can fix it using clear:

    <div id="container">
        <div class="left">Content</div>
        <div class="right">Content</div>
        <br style="clear:both"/>
    </div>
    
    div.left {
        float: left;
        width: 200px;
        border: 1px solid red;
    }
    
    div.right {
        width: 200px;
        border: 1px solid green;
        float:left;
    }
    
    #container{
        border: 1px solid black;
    }
    

    See example

    0 讨论(0)
  • 2021-01-02 07:16
     div.left {
         float: left;
         width: 200px;
        height:200px;
        background:red;
     }
    
     div.right {
        float:right;
         width: 200px;
         height:200px;
        background:blue;
    }
    

    see http://jsfiddle.net/3kUpF/

    Alternatively, if you want them side by side then you can float:left on both see http://jsfiddle.net/3kUpF/1/

    0 讨论(0)
提交回复
热议问题