How to properly float two columns side by side with css

前端 未结 4 1139
[愿得一人]
[愿得一人] 2020-12-29 09:20

This is one of those things I learned a long time ago and never thought much about if I was actually doing it the right way.

Let\'s say we have a structure

相关标签:
4条回答
  • 2020-12-29 10:04

    You display:block along with float:left to float divs next to each other.

    Check working example at http://jsfiddle.net/FhL4u/2/

    To make mainContent fill up rest of the space if only the first div width is known then use percentages on both sideBar and mainContent ex: 20% 80% instead of using fixed width. otherwise you will need a JavaScript solution to achieve a cross browser compatibility.

    Check jQuery solution at http://jsfiddle.net/FhL4u/3/

    0 讨论(0)
  • 2020-12-29 10:14

    use display:flex for two div floats side-by-side

    #wrapper {
        width: 600px;
        display: flex;
    }
    #sideBar {
        display: inline-flex;
        width: 25%;
    }
    #mainContent {
        width: 75%;
        flex: 1;
    }
    
    0 讨论(0)
  • 2020-12-29 10:17

    I'm modifying my answer from here: How to make an inline-block element fill the remainder of the line?

    • Only #sideBar is floated.
    • You can't really tweak this technique to have equal height columns later on, so that's why I asked before answering. (well, you can, but you need to use a background-image for faux columns)

    See: http://jsfiddle.net/qx32C/37/

    #wrapper {
        overflow: hidden; /* clear the float */
    }
    #sideBar {
        width: 100px;
        float: left;
        background: #f0f
    }
    #mainContent {
        overflow: hidden;
        background: #ccc
    }
    

    Why did I replace margin-left: 100px with overflow: hidden on #mainContent?

    0 讨论(0)
  • 2020-12-29 10:20

    using float left or right is not important. you have wrapper with the width of 600px. when you using float for both sidebar and contain inside the wrapper, you must make sure that the width of sidebar and contain (including margin and padding) equal or less than 600px. If not, the second element will be below the first one. Hope this helps ^^

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