css divide width 100% to 3 column

前端 未结 11 622
余生分开走
余生分开走 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:26

    Use CSS calc():

    body {
      margin: 0;
    }
    
    div {
      height: 200px;
      width: 33.33%; /* as @passatgt mentioned in the comment, for the older browsers fallback */
      width: calc(100% / 3);
      display: inline-block;
    }
    
    div:first-of-type { background-color: red }
    div:nth-of-type(2) { background-color: blue }
    div:nth-of-type(3) { background-color: green }

    JSFiddle


    References:

    • How to remove the space between inline-block elements?
    • MDN calc()
    • Can I Use calc()

    Update: as it's 2018. , use flexbox - no more inline-block whitespace issues:

    body {
      margin: 0;
    }
    
    #wrapper {
      display: flex;
      height: 200px;
    }
    
    #wrapper > div {
      flex-grow: 1;
    }
    
    #wrapper > div:first-of-type { background-color: red }
    #wrapper > div:nth-of-type(2) { background-color: blue }
    #wrapper > div:nth-of-type(3) { background-color: green }

    Or even CSS grid if you are creating a grid.

    body {
      margin: 0;
    }
    
    #wrapper {
      display: grid;
      grid-template-columns: repeat(3, 1fr);
      grid-auto-rows: minmax(200px, auto);
    }
    
    #wrapper>div:first-of-type { background-color: red }
    #wrapper>div:nth-of-type(2) { background-color: blue }
    #wrapper>div:nth-of-type(3) { background-color: green }

提交回复
热议问题