css ヘルパー
css ヘルパー (`hono/css`) は、Hono の組み込み CSS in JS(X) です。
`css` という名前の JavaScript テンプレートリテラル内で CSS を記述できます。`css` の戻り値はクラス名になり、class 属性の値として設定されます。その後、`` コンポーネントに CSS の内容が含まれます。
インポート
ts
import { Hono } from 'hono'
import { css, cx, keyframes, Style } from 'hono/css'
`css` 実験的
`css` テンプレートリテラル内で CSS を記述できます。この例では、`headerClass` を `class` 属性の値として使用しています。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` のような擬似クラスは、ネストセレクタ `&` を使用してスタイル設定できます。ネストセレクタに関するMozilla Developer Networkの記事
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` リテラルを使用して `` コンポーネントに 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` は 2 つのクラス名を合成します。
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 を利用できます。