DEV Community

Jp De los Trinos
Jp De los Trinos

Posted on • Edited on

Specificity Matters in Media Queries

A few weeks ago, I was working on a website page's responsive design and was fiddling with the media queries. For some reason, the grid-template-areas property wouldn't adjust when the viewport width hits the indicated size but there were no problems with the other properties that were being changed alongside it.


Consider the Code below (written using sass):

#Initial Properties
.container .contact .contact-form {
    display: grid;
    column-gap: 2rem;
    row-gap: 2.4rem;
    grid-template-areas:
        "name email"
        "subject subject"
        "message message"
        "send send";
}
Enter fullscreen mode Exit fullscreen mode

(NOTE: The .container is nested inside a body and main tag)

@media (max-width: 700px) {
.contact .contact-form {
    background: yellow;
    grid-template-areas:
        "name name"
        "email email"
        "subject subject"
        "message message"
        "send send";
    }
}
Enter fullscreen mode Exit fullscreen mode

(NOTE: The background-color change was only used to show that it's working on the indicated viewport width(700px), but the grid-template-areas does not)

The Result

Initial Result As you can see, the background-color changed as expected but not the grid-template-areas result which should presumably have all the input blocks occupy the entire width of the form.


How I solved this is by adding another parent tag when targeting the .contact-form , namely the .container parent.

#Media Query REVISED
@media (max-width: 700px) {
.container .contact .contact-form {
    background: yellow;
    grid-template-areas:
        "name name"
        "email email"
        "subject subject"
        "message message"
        "send send";
    }
}
Enter fullscreen mode Exit fullscreen mode

Final ResultAdding the .container class allowed the grid-template-areas changes to go through. It doesn't end here though. Oddly enough, even if I don't use the .container class but instead used its parents in its place, namely the <main> or <body> tag, the changes will still go through:

@media (max-width: 700px) {
    main .contact .contact-form {
    }
}

AND

@media (max-width: 700px) {
    body .contact .contact-form {
    }
}
Enter fullscreen mode Exit fullscreen mode

will work, but

@media (max-width: 700px) {
    .contact .contact-form {
    }
}
Enter fullscreen mode Exit fullscreen mode

does not.


Conclusion

I tried recreating this using CSS and SCSS, with the same tags, classes, and nesting (just the very bare minimum) but the same problem didn't present itself. I don't know what was wrong with my previous code but I just concluded that I should be VERY SPECIFIC when using media queries.
.
.
.
(Just my thoughts and experience, Not a tutorial)

Top comments (0)