Utilizing CSS grid and Sass, I implement varying grid layouts for different screen sizes (phone, tablet, desktop). However, on certain pages, I desire the same layouts at slightly larger or smaller screens than others.
Is there a way to achieve this without duplicating styles excessively? My current solution (shown below) functions, but results in repetitive styling.
To elaborate:
I have 3 distinct grids selected according to screen size.
.hero {
&__container {
grid-template-areas:
"header"
"image"
"text";
}
@media min-width: 1000px {
grid-template-areas:
"header header header"
"text ... image"
"text ... image";
}
// additional definitions for this screen size
}
@media min-width: 1300px {
grid-template-areas:
"header header image"
"text ... image"
"text ... image";
}
// other definitions for this size
}
}
&__header {
grid-area: header;
font-size: 2.5rem;
@media min-width: 1000px {
font-size: 2.8rem;
}
@media min-width: 1300px {
font-size: 3.2rem;
}
}
...
}
These are utilized across approximately 20 similar web pages.
<div class="page_a">
<div class="hero">
<div class="hero__container">
<div class="hero__header">...</div>
<div class="hero__text">...</div>
<div class="hero__image">...</div>
</div>
</div>
</div>
The layout remains consistent, however, I wish to transition to different layouts at varying breakpoints based on content specifics like header text length, image size, importance, etc.
What I aim to accomplish is depicted as follows:
.page_a {
.hero {
// retain default settings, no alterations
}
}
.page_c {
.hero {
// longer header requires bigger screen for largest layout switch
// specify that the 1300px layout should be used from 1500px
}
}
The sole workaround I achieved was merely redefining all the grids at each potential breakpoint (default + custom ones), leading to excessive repetition in the code:
.page_c {
.hero {
// utilize 1000px layout also for 1300px - whole process needs to be repeated
@media min-width: 1300px {
grid-template-areas:
"header header header"
"text ... image"
"text ... image";
}
// additional definitions for this size
}
// use 1300px layout for 1500px - entire set of rules has to be reiterated
@media min-width: 1500px {
grid-template-areas:
"header header image"
"text ... image"
"text ... image";
}
// other specifications for this size
}
}
}
This implies that whenever a layout adjustment is made, changes must be applied throughout all instances where it is used at various sizes.