全局样式与 CSS Modules
将全局样式和组件作用域样式应用于构建视觉上一致且可维护的 Next.js 应用。
No configuration found for ID: 823edaa117e57c261203c4ba78d40e898bd6048227dae642670362e565d0f0e8
No configuration found for ID: bb78ce2d88ea0909cebfe01a262e0d18a321037274f196376d506e3992d38756
No configuration found for ID: f5549b7a6e921720a2b501c5b948b671e09374107c5f3c185eafe293a7a43452
显示解决方案
让我们逐步走一遍完整的解决方案。
1. app/globals.css 文件
此文件设置了我们整个应用的全局样式,包括 body 的重置、字体族、背景颜色、文本颜色以及默认链接样式。
添加全局背景颜色
1/* app/globals.css */ 2body { 3 margin: 0; 4 font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, 5 Ubuntu, Cantarell, 'Fira Sans', 'Droid Sans', 'Helvetica Neue', sans-serif; 6 background-color: #e0e0e0; /* 此行已添加 */ 7 color: #333; 8} 9 10a { 11 color: #0070f3; 12 text-decoration: none; 13} 14 15a:hover { 16 text-decoration: underline; 17}
说明:
第 6 行: 我们向
body选择器添加了background-color: #e0e0e0;规则。由于这是在根布局中导入的全局样式表,因此该更改会应用于应用中每一页的背景,提供一致的外观和感觉。
2. app/components/UserProfile.js 文件
此文件定义了一个 UserProfile 组件,使用 Next.js 的 Image 组件和 CSS Module 样式显示用户的头像和姓名。
将作用域样式应用于组件
1// app/components/UserProfile.js 2import Image from 'next/image'; 3import styles from './UserProfile.module.css'; 4 5export default function UserProfile({ name, avatarUrl }) { 6 return ( 7 <div className={styles.card}> 8 <Image 9 src={avatarUrl} 10 alt={`${name}'s avatar`} 11 width={100} 12 height={100} 13 className={styles.avatar} 14 /> 15 <h2 className={styles.name}>{name}</h2> 16 </div> 17 ); 18}
说明:
第 3 行: 我们导入了
UserProfile.module.css文件。这告诉 Next.js 将此样式表作为 CSS Module 处理,并使特殊的styles对象可供我们的组件使用。第 7 行: 我们通过设置
className={styles.card}将.card样式应用于主div。这为组件的容器提供了白色背景、圆角和阴影。第 13 行: 向
<Image>组件添加了className={styles.avatar}属性。这应用了预先编写的样式,使用户头像具有圆形边框。第 15 行: 最后,我们通过
className={styles.name}将.name样式应用于<h2>元素,以控制文本的颜色、大小和间距。