How to place two divs next to each other?

后端 未结 13 1847
孤独总比滥情好
孤独总比滥情好 2020-11-22 05:44

Consider the following code:

相关标签:
13条回答
  • 2020-11-22 06:21

    My approach:

    <div class="left">Left</div>
    <div class="right">Right</div>
    

    CSS:

    .left {
        float: left;
        width: calc(100% - 200px);
        background: green;
    }
    
    .right {
        float: right;
        width: 200px;
        background: yellow;
    }
    
    0 讨论(0)
  • 2020-11-22 06:23

    Float one or both inner divs.

    Floating one div:

    #wrapper {
        width: 500px;
        border: 1px solid black;
        overflow: hidden; /* will contain if #first is longer than #second */
    }
    #first {
        width: 300px;
        float:left; /* add this */
        border: 1px solid red;
    }
    #second {
        border: 1px solid green;
        overflow: hidden; /* if you don't want #second to wrap below #first */
    }
    

    or if you float both, you'll need to encourage the wrapper div to contain both the floated children, or it will think it's empty and not put the border around them

    Floating both divs:

    #wrapper {
        width: 500px;
        border: 1px solid black;
        overflow: hidden; /* add this to contain floated children */
    }
    #first {
        width: 300px;
        float:left; /* add this */
        border: 1px solid red;
    }
    #second {
        border: 1px solid green;
        float: left; /* add this */
    }
    
    0 讨论(0)
  • 2020-11-22 06:23

    Try to use flexbox model. It is easy and short to write.

    Live Jsfiddle

    CSS:

    #wrapper {
      display: flex;
      border: 1px solid black;
    }
    #first {
        border: 1px solid red;
    }
    #second {
        border: 1px solid green;
    }
    

    default direction is row. So, it aligns next to each other inside the #wrapper. But it is not supported IE9 or less than that versions

    0 讨论(0)
  • 2020-11-22 06:25
    1. Add float:left; property in both divs.

    2. Add display:inline-block; property.

    3. Add display:flex; property in parent div.

    0 讨论(0)
  • 2020-11-22 06:29

    You can sit elements next to each other by using the CSS float property:

    #first {
    float: left;
    }
    #second {
    float: left;
    }
    

    You'd need to make sure that the wrapper div allows for the floating in terms of width, and margins etc are set correctly.

    0 讨论(0)
  • 2020-11-22 06:30

    Having two divs,

    <div id="div1">The two divs are</div>
    <div id="div2">next to each other.</div>
    

    you could also use the display property:

    #div1 {
        display: inline-block;
    }
    
    #div2 {
        display: inline-block;
    }
    

    jsFiddle example here.

    If div1 exceeds a certain height, div2 will be placed next to div1 at the bottom. To solve this, use vertical-align:top; on div2.

    jsFiddle example here.

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