Apply CSS by conditioning when two classes are together

Asked

Viewed 116 times

2

I have two situations:

<div class="content">
    <span class="title">Título</span>
    <span class="time">12:00</span>
</div>

and

<div class="content">
    <span class="title">Título</span>
</div>

When "time" exists, I need to apply a style to both the "time" class and the "title" class. And when there is no "time" I need "title" to have another style.

  • If you are building HTML via backend (e.g., PHP + database), it is easier to solve. If not, I think you will only get it via JS.

  • @Sam uncle, nothing that putting a order in the house do not solve :D

  • @hugocsl I don’t know why but I just remembered that car from Maniero :D

  • @hugocsl I hope the question is just a curiosity, because I refuse to imagine that someone will do it in production rs... Much simpler to create 2 classes: one when you have the time and another without the time.

  • @Sam haha as only had the CSS tag I think would have no other option than this... If you know what you are doing is a very consistent solution, but will him know how it will climb...

  • It is pq the classes already comes from fullcalendar. As I can not touch the core of them I made a solution apart!

Show 1 more comment

1 answer

4


To do with a CSS technique using order.

With this you can apply a CSS rule using the selector +

With the order vc will show visually on the screen, the Title before the Time, but in the DOM the Time will come before the Title, so you apply CSS with time+title { seu css }

To use the container father has to be flex or grid, and so you put order: -1; in the title for it to always be the first element on the screen (not in the DOM).

See the example to better understand, note that in the code the Time is before the Title, but in the display on the screen the Title is before the Time

.content {
  display: flex;
}

.title {
  color: red;
  order: -1; /* com isso o title sempre vai vir antes do time na TELA, não no DOM */
}
.time + .title { /* condição que aplica cor diferente no title, caso haja o Time no DOM */
  color: blue; 
}

.time {
  color:green;
}
<div class="content">
  <span class="time">12:00 </span> 
  <span class="title"> Título </span><br>
  <i> quanto tem time o title fica blue</i>
</div>
<br>
<div class="content">
  <span class="title"> Título </span><br>
  <i> quando não tem time o title fica red</i>
</div>

  • 1

    Perfect! Thank you!

  • 1

    @Fernandoissler nice that helped there!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.