Sam Denty
Sam Denty

Reputation: 4085

CSS style td elements depending on td width

I've got two fixed width elements inside a td. On desktops they display next to each other and on smaller displays, they get wrapped so the second element is underneath the first.

How would I target the second element (second red div) only when it's displayed below the first?

Example:

table {
  border: 1px solid #000;
}
table td:nth-child(1) div {
  background: red;
  display: inline-block;
  height: 20px;
  width: 20px;
  margin: 10px;
}
table td:nth-child(2) div {
  background: #777;
  display: inline-block;
  height: 20px;
  width: 200px;
}
.two {
width: 100px;
}
Table 1:
<table>
  <tr>
    <td><div></div><div></div></td>
    <td><div></div></td>
  </tr>
</table>
<br>
Table 2:
<table class="two">
  <tr>
    <td><div></div><div></div></td>
    <td><div></div></td>
  </tr>
</table>

Upvotes: 1

Views: 123

Answers (1)

cjl750
cjl750

Reputation: 4629

Your HTML and CSS aren't "aware" of how your page currently looks, so you can't literally target them depending how whether the second div is wrapped below the first one.

What you can do is figure out when they wrap, and then use a media query.

Playing around in Chrome's console by setting a max-width on the body tag, I found that they do not wrap until 334px wide.

So your styles would look something like this:

@media all and (max-width: 334px) {
  td.WiFi div:nth-child(2) {
    border: 2px solid red; /* or whatever */
  }
}

Now if you had fixed values for the table itself and/or some of its columns, you might be able to work out mathematically when everything wasn't going to fit, and use that as your media query instead. But I don't see a way to do that on your website with the current styling because the only things with a fixed width are the SVGs, and everything else is in percentages. So the whole thing is very flexible, and it's not going to wrap until it absolutely has to. No worries, though, that's generally a good thing.

The only edge scenario you could run into problems with is if your font didn't load correctly, so the user saw the page with some fallback font, because right now the point at which your column wraps is basically dependent on how wide the text in the other columns just happens to be. If a different font was used, you could end up with a different breakpoint, which may or may not cause a broken layout for a few pixels.

That is probably not a practical concern for you, though, because nobody is going to be looking at your site at 334px wide on a desktop (i.e., a device with resizable windows), and phones are basically either 360px+ or 320px wide. The potential problem area in the 330s and 340s doesn't really exist.

Upvotes: 1

Related Questions