Home > Web Front-end > CSS Tutorial > CSS&# only-child instead of Conditional Logic

CSS&# only-child instead of Conditional Logic

DDD
Release: 2024-10-26 11:09:29
Original
611 people have browsed it

In many of the frontend frameworks that I work with, there are options for ternaries or if-branches injected into the HTML logic. This is logic I use a lot. One particular case is to show when there is no data.

I just stumbled on a CSS pattern that makes my life much easier: the :only-child pseudo-class.

React

In React, I would do "something" like this ...

{
  data.length === 0
    ? <div>Nothing to show.</div>
    : <TableWithRecords />
}
Copy after login

Angular

In Angular, I would do "something" like this ...

@if (data.length === 0) {
   <div>Nothing to show.</div>
} @else {
   <TableWithRecords />
}
Copy after login

Using CSS

To put it simply, I have two cases.

  1. There is not data.
  2. There is data.
<h2>No Data Showing</h2>
<ul>
  <li class="handle-no-data">Nothing to show.</li>
  <!-- <li>Data here</li> -->
</ul>

<h2>Data Showing</h2>
<ul>
  <li class="handle-no-data">Nothing to show.</li>
  <li>Data here</li>
</ul>
Copy after login

Using a simple CSS class .single ...

.handle-no-data:not(:only-child) {
  display: none;
}
.handle-no-data:only-child {
  display: flex;
}
Copy after login

This CSS could be simplified to ...

.handle-no-data {
  &:not(:only-child) {
    display: none;
  }
  &:only-child {
    display: flex;
  }
}
Copy after login

Here's the result of the code above ...

CSS

Summary

As you can see, I would have to move the handling of the data to the table level, but the CSS is pretty straight forward to handle a "no data" scenario.

This is exciting!

The above is the detailed content of CSS&# only-child instead of Conditional Logic. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template