css divide width 100% to 3 column

前端 未结 11 544
余生分开走
余生分开走 2020-12-12 21:38

I have a layout where I have 3 columns.

Therefore, I divide 100% by 3.

The result is obviously 33.333....

My goal is perfect

相关标签:
11条回答
  • 2020-12-12 22:30

    A perfect 1/3 cannot exist in CSS with full cross browser support (anything below IE9). I personally would do: (It's not the perfect solution, but it's about as good as you'll get for all browsers)

    #c1, #c2 {
        width: 33%;
    }
    
    #c3 {
        width: auto;
    }
    
    0 讨论(0)
  • 2020-12-12 22:31

    How about using the CSS3 flex model:

    HTML Code:

    <div id="wrapper">
        <div id="c1">c1</div>
        <div id="c2">c2</div>
        <div id="c3">c3</div>
    </div>  
    

    CSS Code:

    *{
        margin:0;
        padding:0;
    }
    
    #wrapper{
        display:-webkit-flex;
        -webkit-justify-content:center;
    
        display:flex;
        justify-content:center;
    
    }
    
    #wrapper div{
        -webkit-flex:1;
        flex:1;
        border:thin solid #777;
    
    }
    
    0 讨论(0)
  • 2020-12-12 22:35

    I have found that 6 decimal places is sometimes required (at least in Chrome) for the 1/3 to return a perfect result.

    E.g., 1140px / 3 = 380px

    If you had 3 elements within the 1140 container, they would need to have a width set to 33.333333% before Chrome's inspector tool shows that they are at 380px. Any less amount of decimal places, and Chrome returns a lesser width of 379.XXXpx

    0 讨论(0)
  • 2020-12-12 22:37

    Just in case someone is still looking for the answer,

    let the browser take care of that. Try this:

    • display: table on the container element.
    • display: table-cell on the child elements.

    The browser will evenly divide it whether you have 3 or 10 columns.

    EDIT

    the container element should also have: table-layout: fixed otherwise the browser will determine the width of each element (most of the time not that bad).

    0 讨论(0)
  • 2020-12-12 22:37

    Just to present an alternative way to fix this problem (if you don't really care about supporting IE):

    A soft coded solution would be to use display: table (no support in IE7) along with table-layout: fixed (to ensure equal width columns).

    Read more about this here.

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