【发布时间】:2021-08-29 12:35:13
【问题描述】:
我使用 CSS 网格和 Sass,并且针对不同的屏幕尺寸(phone、tablet、desktop)使用不同的网格布局。但是对于某些页面,我想要相同的布局,但选择比其他页面稍大或稍小的屏幕。
这样的事情可能吗?还是我从错误的角度接近它?我当前的解决方案(见下文)有效,但重复了很多样式。
更详细的:
我有 3 个根据屏幕尺寸选择的不同网格。
.hero {
&__container {
grid-template-areas:
"header"
"image"
"text";
}
@media min-width: 1000px {
grid-template-areas:
"header header header"
"text ... image"
"text ... image";
}
// other definitions for this screen size
}
@media min-width: 1300px {
grid-template-areas:
"header header image"
"text ... image"
"text ... image";
}
// other definitions for this screen 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;
}
}
...
}
它们被用于大约 20 个类似的网页中。
<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>
布局非常相似,但我想根据内容的具体情况在不同的点切换到不同的布局:标题文本长度、图像的大小和重要性等。
我想做的是这样的:
.page_a {
.hero {
// redefine nothing, use defaults
}
}
.page_c {
.hero {
// the header is longer so we need a bigger screen to switch to the biggest layout
// somehow say that the 1300px layout should be used from 1500px
}
}
我唯一能做的就是简单地重新定义每个可能点的所有网格(默认点+自定义点),这意味着代码非常重复:
.page_c {
.hero {
// use 1000px layout also for 1300px - the whole thing has to be repeated
@media min-width: 1300px {
grid-template-areas:
"header header header"
"text ... image"
"text ... image";
}
// other definitions for this size
}
// use 1300px layout for 1500px - the whole thing has to be repeated
@media min-width: 1500px {
grid-template-areas:
"header header image"
"text ... image"
"text ... image";
}
// other definitions for this size
}
}
}
这意味着每次我改变一些布局时,我都必须去所有使用不同尺寸的地方并改变它。
【问题讨论】:
标签: css responsive-design css-grid grid-layout