我第一次使用Next.JS的CSS模块,它们非常有用。
但当我试图将风格应用于儿童元素时,我遇到了一种奇怪的行为。
例如,如果我有以下HTML
<Offcanvas show={menu} onHide={closeMenu} className={styles.mobile_menu}>
<Offcanvas.Header closeButton className={styles.mobile_menu_header}>
<Offcanvas.Title className={styles.mobile_menu_title}>
<h1>Menu</h1>
</Offcanvas.Title>
</Offcanvas.Header>
<Offcanvas.Body>
<ul className="list-unstyled">
{ links.map((link, key) => (
<li key={"nav-link-" + key} className="mb-3">
<Link href={link.href} className={[styles.link, router.pathname == link.href ? "active" : ""].join(" ")}>{ link.label }</Link>
</li>
)) }
</ul>
</Offcanvas.Body>
</Offcanvas>
这个SCSS
.mobile_menu {
background-color: rgb(57, 70, 78) !important;
color: #fff !important;
}
.mobile_menu_header {
border-bottom: solid 1px rgb(148, 162, 170);
button.btn-close {
filter: brightness(0) invert(1) !important;
opacity: 1 !important;
width: 1.6rem !important;
height: 1.6rem !important;
background-size: 100% !important;
}
}
.mobile_menu_title {
h1 {
font-size: 3.2rem;
}
}
.link {
color: #fff;
text-transform: uppercase;
font-size: 1.7rem;
transition: color 0.3s ease-in-out;
&.active {
border-bottom: solid 1rem rgb(148, 162, 170) !important;
}
&:hover {
color: rgb(148, 162, 170);
}
}
应用于button.btn-close
的属性(通过向Offcanvas.Header
添加closeButton
标志自动生成(没有应用,而且与active
类的链接也没有预期的底部边界。
因此,这让我认为Next.JS的CSS模块中的SASS没有使用嵌套/子/选择器。但是,由于某种原因,.mobile_menu_title
中的h1
是样式化的,当我试图从选择器中删除.btn-close
(只留下button
(时,它被应用了!
那么,这是一个bug还是我不知道的东西?使用SASS的嵌套样式仅适用于";纯";元素,而不是具有类/ID的选择器。
有人能帮我吗?
谢谢!
注意:我使用的是react引导程序包。
好吧,你可以做的是以下
在您的JavaScript文件中
...
<Offcanvas.Header closeButton className={styles.mobile_menu_header}>
...
</Offcanvas.Header>
...
在您的样式文件中
.mobile_menu_header {
border-bottom: solid 1px rgb(148, 162, 170);
:global {
button.btn-close {
filter: brightness(0) invert(1) !important;
opacity: 1 !important;
width: 1.6rem !important;
height: 1.6rem !important;
background-size: 100% !important;
}
}
}
为什么
通过添加:global
规则,您基本上是在告诉您的React应用程序:";在计算出类名为mobile_menu_header
的元素中(实际类名将类似于index_mobile_menu_header_xxxxxxxx
(,找到类名为btn-close
的元素并应用指定的样式";。
像您所做的那样,将所有内容封装在mobile_menu_header
中有助于避免在整个应用程序中覆盖btn-close
,并在该组件中覆盖它们。
当覆盖CSS库的唯一方法是覆盖样式本身时(因此,如果你不能以其他方式自定义库,如样式组件或主题设置(,但你也需要面对CSS模块(导致名称像而不仅仅是类名的模块(,这可以是一种适应策略。