Home > other >  Is it possible to have a default CSS style if no other styles are applied?
Is it possible to have a default CSS style if no other styles are applied?

Time:09-09

So my situation is that I'm working on a personal portfolio project (using React and Django but likely not relevant for this question), and each project is going to have it's own styles. However I want my website to essentially be a catch all for anything I want to do. Therefore the site has it's own unified stylings whilst each project individually might have different styles.

The specific situation is that with buttons. I have added an all: unset; to my base button styles to ensure that I get to style each button type individually (I am also accounting for focus and accessibility in case that's a concern). My hope was to essentially build my own "default" button style that's completely overridden if any styles are applied via a higher selector. So for example:

button {
  all: unset;
  padding: 1rem 2rem;
  background-color: grey;
  color: white;
}

.green {
  // all: unset;
  background-color: green;
}
<button>Submit</button>
<button >Submit</button>

Here, the button on the right has all the same styles but with a different background colour. However ideally what I'd like would be what happens if you uncomment all: unset; in .green, where all styles are removed and you're left with a blank canvas onto which to write again. Obviously adding all: unset; to the class selector gives my desired result, but I was wondering if there was an easier way without having to specify for every new style? Adding multiple all: unset; tags throughout the styles seems untidy but I don't know of any better way unfortunately. Can anyone help?

In coding language, I essentially want the following logic but in CSS:

if (no selectors in element) {
    default-styles;
} else {
    selector-styles;
}

Happy to provide any extra info if necessary.

CodePudding user response:

an idea can be to used the css :not selector on default style to avoid specific class to use it

your default style will do the all: unset but not the specific one

button:not(.green) {
  all: unset;
  padding: 1rem 2rem;
  background-color: grey;
  color: white;
}

.green {
  background-color: green;
}
<button>Submit</button>
<button >Submit</button>

  • Related