skip to Main Content

I’m trying to work with CSS to alternate background color in my divs. I can do that, but which divs display changes. I’d like to be able to alternate only what’s currently visible. Otherwise it’s pretty random what background color appears based on unrelated factors for which divs are visible.

This is what I’m currently trying:

.dialog {
  display:flex;
  flex-direction:row;
  align-items:center;
  background-color: #FFFFFF22;
}
#output-table > .dialog:not([style*="none"]):nth-child(odd) {
  background-color: #FFFFFF11;
}

And the html:

<div id="output-table">
  <div class="dialog">stuff1</div>
  <div class="dialog">stuff2</div>
  <div class="dialog">etc....</div>
</div>

Currently when the page loads all divs are visible, and background-color alternates, but it looks like nothing changes when some divs become invisible (i.e. the order of color alternation is the same and not alternating properly according to visibility).
.dialog is set to display:flex by default. JavaScript may set each individual element as display:flex or display:none, but the elements aren’t individually set when the page is loaded. Thus why I try not([style*="none"]) rather than [style="flex"] as I’m not sure if CSS treats those two cases differently.
I’m sure I could solve things by having js add/remove classes when it changes the display. I just am wondering if there’s some CSS-only solution.

2

Answers


  1. You will have to change your background color with javascript, perhaps using an "invisible" class with a background color property

    Login or Signup to reply.
  2. you can use .dialog:nth-child(odd of :not(.noDisplay)):

    #output-table > .dialog:nth-child(odd of :not(.noDisplay)) {
      background : lightgreen;
      }
    
    .noDisplay {
      display: none;
      }
    
      
    <div id="output-table">
      <div class="dialog">stuff1</div>
      <div class="dialog">stuff2</div>
      <div class="dialog">stuff3</div>
      <div class="dialog">stuff4</div>
      <div class="dialog noDisplay">stuff---5</div>
      <div class="dialog">stuff6</div>
      <div class="dialog">stuff7</div>
      <div class="dialog">stuff8</div>
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search