How Do Redundant CSS Selectors Work?

This is not a request for help with a specific project, but rather an expression of curiosity.

In CSS, let’s say I have two declaration blocks, each with the same sole selector, but each with sets of declarations that are wildly different and do not conflict in any way.

For example,

h1 {
text-align: center;

h1 {
font-family: sans-serif;

Would the above code produce a centered sans-serif heading?

This is correct yes, but generally considered bad practise. Reason being of course that if you had 2 or more selectors for the exact same element, it can make maintenance on the code more difficult as it the behaviour you wish to change for an element could be elsewhere in your script and oftentimes someone wouldn’t assume you have more than one selector.

However to answer the question directly yes, this would work fine as long as the properties didn’t overwrite each other, for example in this codepen we have three h1 selectors in the CSS. We can see that the bottom one will always take precedent (unless !important is used on a property) And if we comment out each selector from the bottom up, the text will change accordingly. We can also see that the text-align and font-family properties are overwritten, however the text will stay blue, as there’s no code further down to overwrite this property.

As I said before it’s generally considered bad practise in normal cases of a single CSS file, however it can be useful when used inside of a media query. If you are using a media query to make a webpage change based on the screen width, you don’t want to have to redefine every element 2 or 3 times over per view, as often it will mostly stay the same with a few font-size changes and such. So there you will have a main selector which has all of your default properties, and then another selector inside of your media query to make the more specific changes required for that device. I’ve created another codepen to demonstrate this, simply resize your web browser or open one on a PC and one on a phone to see the difference and what elements are overwritten.