2

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>

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.

mimo
  • 6,221
  • 7
  • 42
  • 50
  • 2
    Use `inline-flex` instead ...? – CBroe Nov 02 '21 at 10:37
  • Yep, that works (didn't know about inline-flex). Thanks. Can you please add an explanation why are block elements stretched to the full width of table cell? I am really curious and I will accept your answer. – mimo Nov 02 '21 at 10:39

4 Answers4

4

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

Klak031
  • 97
  • 1
  • 1
  • 13
0

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

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

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.

mimo
  • 6,221
  • 7
  • 42
  • 50
-1

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

Marko
  • 114
  • 4