五、Styling
大约 1 分钟约 362 字
(一)Global Styles
styles/globals.css
1.html,
body {
padding: 0;
margin: 0;
}
a {
color: inherit;
text-decoration: none;
}
* {
box-sizing: border-box;
}
h2 {
color: orange;
}
pages/_app.js
2.import "../styles/globals.css";
function MyApp({ Component, pageProps }) {
return <Component {...pageProps} />;
}
export default MyApp;
pages/about.js
3.function About() {
return <h2>About Page</h2>;
}
export default About;
pages/contact.js
4.function Contact() {
return <h2>Contact Page</h2>;
}
export default Contact;
(二)Component Level Styles
styles/About.module.css
1..highlight {
color: red;
}
styles/Contact.module.css
2..highlight {
color: blue;
}
pages/about.js
3.import styles from "../styles/About.module.css";
function About() {
return <div className={styles.highlight}>About Page</div>;
}
export default About;
pages/contact.js
4.import styles from "../styles/Contact.module.css";
function Contact() {
return <div className={styles.highlight}>Contact Page</div>;
}
export default Contact;
(三)Sass Support
yarn add sass
styles/_colors.scss
1.$orange: orange;
$purple: purple;
styles/About.module.scss
2.@import "colors";
.highlightscss {
color: $orange;
}
styles/Contact.module.scss
3.@import "colors";
.highlightscss {
color: $purple;
}
pages/about.js
4.import styles from "../styles/About.module.scss";
function About() {
return <div className={styles.highlightscss}>About Page</div>;
}
export default About;
pages/contact.js
5.import styles from "../styles/Contact.module.scss";
function Contact() {
return <div className={styles.highlightscss}>Contact Page</div>;
}
export default Contact;
(四)CSS in JS
yarn add styled-components
pages/css-in-js.js
1.import styled from "styled-components";
const Title = styled.h1`
font-size: 50px;
color: ${({ theme }) => theme.colors.primary};
`;
function CSSJS() {
// return <h2 style={{ color: "red" }}>Hello World</h2>;
return <Title>Styled Component</Title>;
}
export default CSSJS;
pages/_app.js
2.import "../styles/globals.css";
import { ThemeProvider } from "styled-components";
const theme = {
colors: {
primary: "#D8152A",
},
};
function MyApp({ Component, pageProps }) {
return (
<ThemeProvider theme={theme}>
<Component {...pageProps} />
</ThemeProvider>
);
}
export default MyApp;
(五)Summary
- Global:全局样式
- 在项目中,需要在
pages/_app.js
中导入全局样式文件
- 在项目中,需要在
- Component Level:组件样式
NextJS
支持使用[name].module.css
命名的 CSS 模块
- SASS Support:SASS 样式
- 需要安装
sass
包
- 需要安装
- CSS-in-JS Solutions:解决方案
- 使用内联样式和样式化组件,需要安装
styled-components
包
- 使用内联样式和样式化组件,需要安装