Reputation: 25
I'm just learning html and css and have just completed a landing page project. When I reviewed my css at the end, I realised that I had multiple media queries all for the same conditions (max-width) but applied to different elements.
I know that you can put multiple elements within a media query but what is best practice?
Currently I have each separate media query located just after the setup css for that element
i.e. #header is followed by @media (max-width:640px) #header{stuff;}}
Upvotes: 2
Views: 2142
Reputation: 808
Media queries were introduced in CSS3 are used for responsive CSS over different media types. Since usually the CSS code itself is applied for describing the presentation of the document or page, responsiveness is a separate feature altogether, so usually they are kept separate at the end of the CSS formatting codes. However, let me answer this question by stating the usage of both of the formats mentioned in the question.
Most templates of CSS available online usually keep their media queries at the bottom of the entire code making it easier to access and work with the responsiveness feature. Whenever the focus is more on "chasing device-widths" then this type of coding practice helps.
As observed, this allows to group together many basic CSS attributes that are applied over many elements.
Also, considering the cascading nature of CSS, the styling below usually (not always, refer this to know more) overwrites the styling present above. With @media
queries present at the bottom of the stylesheet, it allows easy overwriting of relevant styles present above.
Finally ,as mentioned by @rguttersohn, media queries along with @keyframes
are kept at the end with @keyframes
usually above @media
. This makes coding cleaner and easier to comprehend by others as well.
If styling is more layout-centric, it's highly useful to place @media
queries next to their styling counterparts. This allows ease in editing the style and its corresponding @media
query both in a single go.
This does mean that there is slightly more code, but these too can be cut down by grouping at breakpoints and section ends.
This type of styling is rarely seen in templates available online, however it's an ongoing trend.
To Summarize: I personally am of the opinion to keep all of the @media
queries together at the bottom, but if I had to divide the labor of styling, I would opt for keeping the styles and @media
queries together.
Also, given the broad and opinionated scope of this question, I think no answer can determined as right or wrong. I hope this answer brings enough light and information to the question.
Upvotes: 8