Home > front end >  Prevent display: flex from stretching to full width of table cell
Prevent display: flex from stretching to full width of table cell

Time:11-03

I have a table with minimum width and variable number of columns. But the first column will always have the same content, container with couple icons stack together.

I need to use display: flex on the container, but this will stretch it to the full width of column, which will break my layout, please see example bellow:

table {
  width: 500px;
  background-color: tan;
}

.stack-container {
  position: relative;
  display: flex;  /* This is the troublemaker */
}

.icon1 {
  font-size: 22px;
}

.icon2 {
  position: absolute;
  right: -2px;
  bottom: -3px;
}
<table>
  <tr>
    <td>
      <span class="stack-container">
        <span class="icon1">A</span>
        <span class="icon2">o</span>
      </span>
    </td>
    <td>Two</td>
  </tr>
</table>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

How to prevent the .stack-container with display: flex to stretch to full width of a table cell and make it stretch only to the width of it's content?

Example of what I want to achieve:

enter image description here

Note1: When .stack-container is display: block it's stretched as well.

Note2: When .stack-container is display: inline, then it's not stretched to the full width of a table cell.

CodePudding user response:

To be honest i am not sure what you want to do exactly but try to use inline-flex instead of flex

CodePudding user response:

You can try to use these styles for the first td.

td:first-child {
  width: 1px;
  white-space: nowrap;
}

CodePudding user response:

Thanks for the answers and suggestions to use display: inline-flex, this was the value I was looking for.

I would like to elaborate on, why my .stack-container got stretched, when using display: flex (which created block-level box). Here is the answer, which describes it pretty well: Difference between flex and inline-flex.

Especially this part here:

The differences between block layout and inline layout are outside the scope of this question, but the one that stands out the most is auto width: block-level boxes stretch horizontally to fill their containing block, whereas inline-level boxes shrink to fit their contents.

CodePudding user response:

In this case, putting display: flex in table as well should make its contents not go full width. Check out this pen.

  • Related