skip to Main Content

For example, I have 5 elements:

  <span style="width:100%;">
    <div>1111111111</div>
    <div style="width:100%;background-color:red;">2222222222</div>
    <div>3333333333</div>
    <div style="width:100%;background-color:red;">4444444444</div>
    <div>5555555555</div>
  </span>

Which I want them to be enclosed into a row, and then the second and forth element expand to fill the remain width, which the second and forth element would have same width. How can I do it?

I tried:

<table style="width:100%;">
  <tr>
    <td style="white-space:nowrap;">1111111111</td>
    <td style="width:100%;background-color:red;">2222222222</td>
    <td style="white-space:nowrap;">3333333333</td>
    <td style="width:100%;background-color:red;">4444444444</td>
    <td style="white-space:nowrap;">5555555555</td>
  </tr>
</table>

Which the second element expands to "bully" the forth element, which is not working. (Note: it is not necessary to use table, just I think I can achieve the result and then use it, but stills not working)

2

Answers


  1. Set the other three cells to a common width and leave 2 and 4 undefined. The result will be that both 2 and 4 will fill the remaining space equally.

    <table style="width:100%;">
      <tr>
        <td style="width:10%;">1111111111</td>
        <td style="background-color:red;">2222222222</td>
        <td style="width:10%;">3333333333</td>
        <td style="background-color:red;">4444444444</td>
        <td style="width:10%;">5555555555</td>
      </tr>
    </table>
    Login or Signup to reply.
  2. You can use a combination of flex-grow and flex-basis to achieve this. Note that the second and fourth divs below are the same width as each other, even when the remaining space in the parent is different.

    <div style="display: flex; width: 200px;">
      <div style="background: red;">1</div>
      <div style="background: orange; flex-basis: 1; flex-grow: 1;">2</div>
      <div style="background: yellow;">3</div>
      <div style="background: green; flex-basis: 1; flex-grow: 1;">4</div>
      <div style="background: blue;">5</div>
    </div>
    <br/>
    <div style="display: flex; width: 200px;">
      <div style="background: red;">1111</div>
      <div style="background: orange; flex-basis: 1; flex-grow: 1;">2</div>
      <div style="background: yellow;">3333</div>
      <div style="background: green; flex-basis: 1; flex-grow: 1;">4</div>
      <div style="background: blue;">5555</div>
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search