光輝咖碼

架設網站的起點

搜尋

如何讓 Footer 保持在網頁底部

sea, beach, ocean

有時候網頁內容高度不夠,會造成 footer 定位在網頁中間很不好看,如果你使用的是 Astra 或 OceanW P 佈景主題,可以參考以下方式可將 footer 自動定位在網頁底部。

如何讓 Astra Footer 保持在網頁底部

Astra 沒有方便的地方設定,必須要在 functions.php 加上一段程式。

add_action( 'wp_footer', 'astra_footer_align_bottom' );
function astra_footer_align_bottom () {
	?>
	<script type="text/javascript">
		document.addEventListener(
			"DOMContentLoaded",
			function() {
				fullHeight();
			},
			false
			);
		function fullHeight() {
			var headerHeight = document.querySelector("header").clientHeight;
			var footerHeight = document.querySelector("footer").clientHeight;
			var headerFooter = headerHeight + footerHeight;
			var content = document.querySelector("#content");
			content.style.minHeight = "calc( 100vh - " + headerFooter + "px )";
		}
	</script>
	<?php
}

儲存即可看看效果。

如果你有使用 Astra Pro 專業版主題,可以新增 Custom Layout。

step 1

進入 Astra Options -> Custom Layouts

Astra theme options

step 2

點擊【Add New】

Astra custom layouts step 1

step 3

點擊【Enable Code Editor】

step 4

Astra layouts code editor
  1. 輸入 layout 名稱
  2. 貼上程式碼
<script type="text/javascript">
	document.addEventListener(
		"DOMContentLoaded",
		function() {
			fullHeight();
		},
		false
		);
		function fullHeight() {
			var headerHeight = document.querySelector("header").clientHeight;
			var footerHeight = document.querySelector("footer").clientHeight;
			var headerFooter = headerHeight + footerHeight;
			var content = document.querySelector("#content");
			content.style.minHeight = "calc( 100vh - " + headerFooter + "px )";
		}
</script$gt;

step 5

Astra custom layout settings
  1. Layout 選擇 Hooks
  2. Action 選擇 wp_footer
  3. Display On Entire Website

儲存即可看看效果。

如何讓 OceanWP Footer 保持在網頁底部

進入選單 – Appearance -> Customize -> Footer Widgets

將選項【Fixed Footer】改成 ON,footer 就會自動移到網頁底部。

Astra footer widgets

使用 flex 技巧,純 CSS Sticky Footer

#HTML

<body class="Site">
  <header>…</header>
  <main class="Site-content">…</main>
  <footer>…</footer>
</body>

很簡單的將網頁分成 3 個區塊。

#CSS

.Site {
  display: flex;
  min-height: 100vh;
  flex-direction: column;
}

.Site-content {
  flex: 1;
}

利用 flex 從上到下排列,設定最小高度為畫面高度,加上自動增長空間,讓主要網頁內容自動延展,Footer 就自動被壓在網頁底部。

參考來源:Sticky Footer