LoginSignup
6
1

【Laravel】独自のCSSファイルを読み込む方法

Last updated at Posted at 2023-08-23

publicフォルダ内にCSSファイルを格納する

①publicフォルダ内にcssフォルダを作成する。
②cssフォルダ内に、style.cssを作成する。

viewでcssファイルを読み込む

○○.blade.phpのheadタグ内に以下のように記述する。

○○.blade.php
<link rel="stylesheet" href="{{ asset('/css/style.css') }}">

assetヘルパー:publicフォルダ内のファイルにアクセスできる(URLを取得する)。引数はpublicフォルダをルートにしたパスを記述する。

resourcesフォルダにcssファイルを置かない理由

resourcesフォルダに置くファイルは、外部に公開されないファイルを置くため。

・resourcesフォルダ:外部に公開されないコンパイル前のファイルを置く。
・publicフォルダ:外部からアクセスしても問題ないファイルを置く。(例:通常のcssファイル、jsファイル、画像ファイルなど)

特定のファイルだけcssファイルを読み込む方法

①親ビュー(resources/views/layouts/app.blade.php)に以下のように記述する。

app.blade.php
@stack('styles')  // 'styles'は任意の文字列

※ファイルを読み込みたい場所に記述する。
例:cssファイル→headタグ内
  jsファイル→bodyタグ内の一番最後

②子ビューに以下のように記述する。(例:index.blade.phpなど)

index.blade.php
@push(`styles`)  // 'styles'は@stack()の引数に指定した文字列を記述する
    <link rel="stylesheet" href="{{ asset('/css/style.css') }}"
@endpush

※記述する位置は@extends()@section()の間。

6
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
1