Div width 100% minus fixed amount of pixels

后端 未结 10 2063
猫巷女王i
猫巷女王i 2020-11-28 17:57

How can I achieve the following structure without using tables or JavaScript? The white borders represent edges of divs and aren\'t relevant to the question.

10条回答
  •  失恋的感觉
    2020-11-28 18:12

    You can make use of Flexbox layout. You need to set flex: 1 on the element that needs to have dynamic width or height for flex-direction: row and column respectively.

    Dynamic width:

    HTML

    1
    2
    3

    CSS

    .container {
      display: flex;
    }
    .fixed-width {
      width: 200px; /* Fixed width or flex-basis: 200px */
    }
    .flexible-width {
      flex: 1; /* Stretch to occupy remaining width i.e. flex-grow: 1 and flex-shrink: 1*/
    }
    

    Output:

    .container {
      display: flex;
      width: 100%;
      color: #fff;
      font-family: Roboto;
    }
    .fixed-width {
      background: #9BCB3C;
      width: 200px; /* Fixed width */
      text-align: center;
    }
    .flexible-width {
      background: #88BEF5;
      flex: 1; /* Stretch to occupy remaining width */
      text-align: center;
    }
    1
    2
    3


    Dynamic height:

    HTML

    1
    2
    3

    CSS

    .container {
      display: flex;
    }
    .fixed-height {
      height: 200px; /* Fixed height or flex-basis: 200px */
    }
    .flexible-height {
      flex: 1; /* Stretch to occupy remaining height i.e. flex-grow: 1 and flex-shrink: 1*/
    }
    

    Output:

    .container {
      display: flex;
      flex-direction: column;
      height: 100vh;
      color: #fff;
      font-family: Roboto;
    }
    .fixed-height {
      background: #9BCB3C;
      height: 50px; /* Fixed height or flex-basis: 100px */
      text-align: center;
      display: flex;
      flex-direction: column;
      justify-content: center;
    }
    .flexible-height {
      background: #88BEF5;
      flex: 1; /* Stretch to occupy remaining width */
      text-align: center;
      display: flex;
      flex-direction: column;
      justify-content: center;
    }
    1
    2
    3

提交回复
热议问题