LoginSignup
4

More than 1 year has passed since last update.

headerとflashの間にできた謎の余白を消す(Devise, Bootstrap)

Last updated at Posted at 2020-03-23

はじめに

(*注意:この記事は学習の一環として実装した物の一部を記事にしています。本記事には正しくない情報、方法を含んでいる可能性があります。)

先日投稿したこちら
Bootstrap + jQueryを使ってFlashなどの
<button>xボタン</button>をクリックした時にFlashを閉じる機能を実装しました。
ただ、ブラウザ場で確認すると、
Flashが消える前、後、双方で との間に余白がないようにぴったり合わしているにも関わらず
<header>flashの間に余白が発生していました。

この余白を無くすことができたので紹介します。

開発環境

  • bootstrap-sass (3.3.7)
  • devise (4.7.1)
  • jquery-rails (4.3.1)
  • rails (5.2.4.1)

前置き (layoutのデザイン)

header.html
<header class= "header-layout navbar navbar-fixed-top navbar-inverse">
  • Bootstrapのnavbar-fixed-topを使ってheaderを固定しております。
  • headerの下の<%= yield%>には画面いっぱいの背景画像を設置した表紙のようになっております。
  • headerの下にHome画面レイアウトの背景画像がぴったりになるように<body>padding: top;でしっかり合わせてあります。)

  • (余白ができていた時のパターン↓)

application.html.erb
<body>
  <%= render 'shared/header'%>
  <%= notice %> //ここ
  <%= alert %> //ここ
<body>

*おそらく、ユーザーがログイン後にflash[:notice]が呼び出された場合、flash[:alert]は、余白としてflash[:norice]の上に表示されていました。

if構文(余白消えない。)

まずこちらを参考にしてみた
https://whatsupguys.net/programming-school-dive-into-code-learning-47/]

app/views/shared/_flash_messages.html.erb

<% if notice %>
  //条件
<% elsif alert %>
 //条件
<% end %>

上記のように条件を組んでブラウザ場の検証を確認しても

ブラウザ場の検証(要素)
<header> </header>
  "       "   //謎の余白
<class= "alert">
  "ログインしました" //flash[:notice]
</>

flashは表示できているけれど<header>flashが呼ばれる<class= "alert">の間に" "と表示され、余白の原因になっています。
おそらく" "の部分は表示されなかったflash[alert]だと思います。
if構文を使って条件を書いても、、余分な余白は表示されたままでした。

解決方法

解決方法を調べてみました。
まず、deviseとBootstrapを組み合わせる祭、Bootstrapには、
deviseのkeyである[:notice],[:alert]に対応したクラスがないので、keyを置き換えることが最善です。

こちらを参考に
(https://hachy.github.io/2019/10/15/flashes-with-devise-and-bootstrap.html)

app/helpers/users_helper.rb
module UsersHelper
#Bootstrapに対応できるdevise flash[notice][alert]を変更する
  def bootstrap_alert(key)
    case key
      when "alert"
       "warning"
      when "notice"
        "success"
      when "error"
       "danger"
    end
  end
end

:alert:warning,:notice:successに変更する為にヘルパーメソッドを作成しています。(devise userモデルを使っているのでそのヘルパーを利用しています。)

Flashの変更

変更前↓ (deviseのデフォルト)

application.html.erb
<body>
  <%= render 'shared/header'%>
  <%= notice %> //ここ
  <%= alert %>  //ここ
<body>

変更後↓

app/views/shared/_flash_messages.html.erb
<% flash.each do |key, value| %>
  <div class="alert alert-<%= bootstrap_alert(key)%> close-flash">
    <%= value %>
    <button type="button" class="close close-button" data-dismiss="alert">
      &times;
    </button>
  </div>
<% end %>
  • deviseのデフォルトflashを変更し、Bootstrapに組み合わせれるように作ったヘルパーメソッドbootstrap_alert(key)を使ってdevise flash[:key]を変更。

これでFlash[:key]がしっかりBotstrapにも適用でき、余分な" "が呼び出されることなく、特定のflash[:key]だけが呼び出され余白も消えました。

参考にしたサイト

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
4