css 輔助工具
css 輔助工具 - hono/css
- 是 Hono 內建的 CSS in JS(X)。
您可以在名為 css
的 JavaScript 樣板字串中撰寫 CSS。 css
的回傳值將會是類別名稱,並設定為 class 屬性的值。 <Style />
元件將會包含 CSS 的值。
匯入
ts
import { Hono } from 'hono'
import { css, cx, keyframes, Style } from 'hono/css'
css
實驗性
您可以在 css
樣板字串中撰寫 CSS。在此範例中,它使用 headerClass
作為 class
屬性的值。別忘了加入 <Style />
,因為它包含 CSS 內容。
ts
app.get('/', (c) => {
const headerClass = css`
background-color: orange;
color: white;
padding: 1rem;
`
return c.html(
<html>
<head>
<Style />
</head>
<body>
<h1 class={headerClass}>Hello!</h1>
</body>
</html>
)
})
您可以使用巢狀選取器 &
來設定偽類別樣式,例如 :hover
ts
const buttonClass = css`
background-color: #fff;
&:hover {
background-color: red;
}
`
擴充
您可以透過嵌入類別名稱來擴充 CSS 定義。
tsx
const baseClass = css`
color: white;
background-color: blue;
`
const header1Class = css`
${baseClass}
font-size: 3rem;
`
const header2Class = css`
${baseClass}
font-size: 2rem;
`
此外, ${baseClass} {}
的語法允許巢狀類別。
tsx
const headerClass = css`
color: white;
background-color: blue;
`
const containerClass = css`
${headerClass} {
h1 {
font-size: 3rem;
}
}
`
return c.render(
<div class={containerClass}>
<header class={headerClass}>
<h1>Hello!</h1>
</header>
</div>
)
全域樣式
名為 :-hono-global
的偽選取器允許您定義全域樣式。
tsx
const globalClass = css`
:-hono-global {
html {
font-family: Arial, Helvetica, sans-serif;
}
}
`
return c.render(
<div class={globalClass}>
<h1>Hello!</h1>
<p>Today is a good day.</p>
</div>
)
或者您可以使用 css
字串在 <Style />
元件中撰寫 CSS。
tsx
export const renderer = jsxRenderer(({ children, title }) => {
return (
<html>
<head>
<Style>{css`
html {
font-family: Arial, Helvetica, sans-serif;
}
`}</Style>
<title>{title}</title>
</head>
<body>
<div>{children}</div>
</body>
</html>
)
})
keyframes
實驗性
您可以使用 keyframes
來撰寫 @keyframes
的內容。在此範例中, fadeInAnimation
將會是動畫的名稱
tsx
const fadeInAnimation = keyframes`
from {
opacity: 0;
}
to {
opacity: 1;
}
`
const headerClass = css`
animation-name: ${fadeInAnimation};
animation-duration: 2s;
`
const Header = () => <a class={headerClass}>Hello!</a>
cx
實驗性
cx
組合了兩個類別名稱。
tsx
const buttonClass = css`
border-radius: 10px;
`
const primaryClass = css`
background: orange;
`
const Button = () => (
<a class={cx(buttonClass, primaryClass)}>Click!</a>
)
它也可以組合簡單的字串。
tsx
const Header = () => <a class={cx('h1', primaryClass)}>Hi</a>
提示
如果您使用 VS Code,可以使用 vscode-styled-components 來為 CSS 標記的字串提供語法高亮和 IntelliSense。