Divide Width of Element Between Child Divs With CSS

前端 未结 4 1214
南笙
南笙 2021-02-01 18:31

I have a varying number of inline-block divs that I want to collectively take up 100% of their parent. Can this be done without JavaScript? The only way I can think o

4条回答
  •  刺人心
    刺人心 (楼主)
    2021-02-01 18:47

    I'd like to expound on @lingeshram's answer. Flexboxes have come so far that I think it's really the way to do it now. If you have to support old browsers, be sure to check caniuse first.

    .container {
      display: flex; /* or inline-flex */
    }
    
    .col {
      flex-grow: 1;
      border: 1px solid #000;
    }
    
    .col2x {
      flex-grow: 2;
      border: 1px solid #000;
    }
    Evenly split three children
    
    Inner 1 Inner 2 Inner 3

    Evenly split two children
    Inner 1 Inner 2

    Split three children, but the middle is twice the size of the others
    Inner 1 Inner 2 Inner 3

    Here is a pretty good guide to the different ways you can use flexbox.

提交回复
热议问题