Quantcast
Channel: CSSタグが付けられた新着記事 - Qiita
Viewing all articles
Browse latest Browse all 8732

Gatsby:CSS書き方とファイル分割の仕様

$
0
0

Gatsby:CSS書き方とファイル分割の仕様

自分で作成したCSSの作り方は以下の通り。React特有の書き方…。

// index.jsimportReactfrom"react"import{Link}from"gatsby"importLayoutfrom"../components/layout"importImagefrom"../components/image"importSEOfrom"../components/seo"import{Container,Row,Col,Badge,Accordion,Card,Button}from'react-bootstrap'consth1Size={     // 自分でつけた任意の名前fontSize:'1.25rem',// font-sizeとするところfontSizeとする。React特有の書き方lineHeight:1.75// line-heightとするところlineHeight}consth2Size={marginTop:'1.25rem',fontSize:'1.1rem',color:'#999999',lineHeight:1.75}constfontSmallCrimson={color:'crimson',fontSize:'small'}constfontSmall={fontSize:'small',}constfontCrimson={color:'crimson',}constfontGray={color:'#777777',}constlineSpace={marginTop:20,}constIndexPage=()=>(<h1style={h1Size}>ギャツビー</h1>・・・以下略・・・


ファイル分割したい

JSファイルがどんどん長くなるのでファイル分割したい。

global.css

プロジェクト全体にあてるCSSは以下のやり方で(bootstrapを使用している場合はいらない作業かも)

  1. まずsrc/stylesフォルダを作成。
  2. stylesフォルダの下にglobal.cssを作成。
  3. global.cssにCSSを記述

styles/global.css

h1{color:FireBrick;}
  1. gatsby-browser.jsに以下のように記述
import"./src/styles/global.css"

この例では全ページのH1見出しをFireBrick色にしてる。
index.jsなどの表示コンポーネントにimport文はいらない。

コンポーネントごとのCSS

index.jsだったらindex.module.cssという名前のファイルを作成する。こうやってファイル名を同じにするだけで、いわゆるAngularにおけるコンポーネント4セット(html, css, ts, spec.ts)のうちのcssファイルだと認識される。

そこに例えば以下のようにマイCSSを記述。

/*index.module.css*/ .h1Size{font-size:1.25rem;line-height:1.75;}.h2Size{margin-top:1.25rem;font-size:1.1rem;color:#999999;line-height:1.75;}.fontSmallCrimson{color:crimson;font-size:small;}.fontSmall{font-size:small;}.fontCrimson{color:crimson;}.fontGray{color:#777777;}.fontRed{color:red}.fontBule{color:steelblue;}.divLineSpace{margin-top:20;}

でJS内のHTMLは以下のように。

//index.jsimportStylesfrom'./index.module.css'・・・略・・<h1className={Styles.h1Size}>ギャツビー</h1>
<spanclassName={Styles.fontSmall}>Gatsby</span>
・・・略・・

import Styles~文の挿入も必要なくしてくれると嬉しい。

以上。



参考:
Adding global styles without a layout component
Gatsby.jsで静的なWebサイトをサクッと作る(CSS・SCSS篇)


Viewing all articles
Browse latest Browse all 8732

Latest Images

Trending Articles

<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>