Solution 1 :

th elements inherently have a display value of display: table-cell, so changing them to display: flex will have dramatic consequences, as you’ve seen.

1. Try ‘inline-flex’ instead of ‘flex’

Like display: block, display: flex elements won’t naturally lie next to each other.

Like display: inline-block, however, display: inline-flex elements will.

This probably won’t be 100% right either, as table cells (including headers) behave differently from inline elements.

2. (Preferred) Use another element inside the th

<th>
  <div class="header-inner">
    <p>col name</p>
    <ArrowDown />
  </div>
</th>
.header-inner {
  display: flex;
}

While this adds another element to the DOM, it’s probably the safer approach. You aren’t disrupting the inherent layout properties of the <th> elements, and you get the expected flexbox behavior you’re after.

In general, if you’re trying to achieve a complicated layout with minimal elements, and it’s not behaving as you’d like, try separating your CSS concerns. Let the table headers have their naturally opinionated layout properties, and add your complications to a separate element.

Solution 2 :

I try this

<table>
  <tr>
    <th><span>A</span><span>B</span></th>
    <th><span>A</span><span>B</span></th>
  </tr>
</table>

table {
 width: 500px;
}
th {
  border: 1px solid #ccc;
  width: 200px;
  display: inline-flex;
  justify-content: space-between;
  align-items: center;
}

And it works

Problem :

I’m making a React app and I want to add an icon to the th tag. So far I have:

<th><p>col name</p><ArrowDown /></th>

I want text and icon to be vertically centered, so I apply flexbox to th:

th {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

And that’s what I see:
enter image description here

Anyone know what’s wrong?

By

Leave a Reply

Your email address will not be published. Required fields are marked *