【jQuery】下に固定要素を置くのでフッターの下を自動でズラす

デザオ
ページの下に申し込みボタンをずっと表示させたいのですがフッターが隠れちゃうのですよねー、どうにかなりませんかねー?
デザコト
自動でフッターの下をズラしちゃいましょうー

さっそく実装してみる

コードを見る(HTML・CSS・jQuery)

HTML

<section class="cta">
  <div class="cta_area">
    <div class="cta_box">
      <a href="https://125naroom.com/web/3982" target="_blank" class="_a">詳しくはこちら</a>
    </div>
  </div>
</section>

CSS

/*=========
.cta
=========*/

.cta {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  width: 100%;
  background-color: rgba(43, 42, 39, 0.8);
  border-top: 3px solid #e8dc6a;
  z-index: 2;
}
.cta_area {
  padding: 0 30px;
  margin-top: 0.8rem;
  margin-bottom: 0.8rem;
}
.cta_box {
  display: flex;
  justify-content: center;
}

/* ボタン(見た目。なくても動きます) */
a._a {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  max-width: 300px;
  margin: 0 auto;
  padding: 2.0em 1.0em;
  border: 1px solid #2b2a27;
  background: linear-gradient(to right, #ffffff 50%, #2b2a27 50%);
  background-size: 200% auto;
  box-sizing: border-box;
  color: #2b2a27;
  font-size: 14px;
  text-decoration: none;
  text-align: center;
  transition: .3s;
  position: relative;
}
a._a:after {
  content: "";
  position: absolute;
  right: -5px;
  bottom: -5px;
  width: 100%;
  height: 100%;
  border-right: 1px solid #e8dc6a;
  border-bottom: 1px solid #e8dc6a;
}
a._a:hover {
  color: #ffffff;
  background-position: -100% 0;
}

/* 動きを減らす設定のとき */
@media (prefers-reduced-motion: reduce) {
  a._a { transition: none; }
}

jQuery

フッターをズラすというよりも、bodyの下を自動でズラすって感じですね。

// =================
// CTA
// =================
$(function(){
  if ($('.cta').length) {
    setCta();
    $(window).on({ 'load': setCta, 'resize': setCta });
  }
  function setCta(){
    $('body').css('padding-bottom', $('.cta').outerHeight());
  }
});

メモ

jQueryのことで何かわからないことがあればjQueryの日本語リファレンスサイトがあるので一度チェックしてみるのをおすすめします。

さいごに

デザオ
おー、すごーい
デザコト
ヘッダーの上をズラしたい場合はちょっと応用しちゃえばオッケーですねー

ふたりの小言

関連記事

デザコトauthor

あ、いいな、と思うWebデザインを紹介しています。デザインの参考に。やさしいデザインが多いです。Webデザインギャラリー『デザインのこと - Web design gallery』を運営しています。