Home > Software engineering >  CSS class with nested elements
CSS class with nested elements

Time:05-10

I want to display table elements as blocks only in a specific class without using a class on every single sub-element of the table.

What I've tried:

@media only screen and (max-width: 650px)
{
  .contactform 
  {
    table, thead, tbody, th, td, tr {
      display: block;
   }
}
<table >
  <tr>
    <td>
      <label> First Name </label>
    </td>
    <td>
      <label> Last Name </label>
    </td>
  </tr>
  <tr>
    <td>
      <label> E-Mail </label>
    </td>
    <td>
      <label> Phone </label>
    </td>
  </tr>
</table>

CodePudding user response:

To avoid using a class on every single 'sub-element' within the table you can use the :is() pseudo class to target certain descendants within your given class.

One issue is that by default the browser styles table elements... as a table. So you might have to flip your media query around

@media only screen and (min-width: 650px) {
  .contactform,
  .contactform :is(table, thead, tbody, th, td, tr) {
    display: block;
  }
}
<table >
  <tr>
    <td>
      <label> First Name </label>
    </td>
    <td>
      <label> Last Name </label>
    </td>
  </tr>
  <tr>
    <td>
      <label> E-Mail </label>
    </td>
    <td>
      <label> Phone </label>
    </td>
  </tr>
</table>

Or for best browser compatibility:

@media only screen and (min-width: 650px) {
  .contactform,
  .contactform table,
  .contactform thead,
  .contactform tbody,
  .contactform th,
  .contactform td,
  .contactform tr {
    display: block;
  }
}
<table >
  <tr>
    <td>
      <label> First Name </label>
    </td>
    <td>
      <label> Last Name </label>
    </td>
  </tr>
  <tr>
    <td>
      <label> E-Mail </label>
    </td>
    <td>
      <label> Phone </label>
    </td>
  </tr>
</table>

  • Related