Common Header & Footer in HTML

Header and footer are an important part of the website which helps in navigation. When using an HTML based website, each separate page of the website have its own header and footer content. Problem arises when we want to change some element of header and footer as we will have to manually make the chances in all pages.

So the best approach would be a centralized header and footer code which can be inserted in all pages of your website. So any change made dot the centralized header and footer code would reflect on all pages.

Unfortunately, HTML does not directly support such inserts. So here is a simple trick to achieve this.

Step 1: Create a header or footer file; here we are creating a footer file named footer.html and place your footer html content inside.

<!-- footer.html -->
<footer id="footer">
    <!-- Your entire footer content goes here -->
</footer>

A client-side approach, using JavaScript, can be used as shown below

<!-- index.html -->
<!DOCTYPE html>
<html>
<head>
    <title>Your Page Title</title>
</head>
<body>
    <!-- Your page content here -->

    <!-- Placeholder for the footer -->
    <div id="footer-placeholder"></div>

    <!-- Include the footer using JavaScript -->
    <script>
    fetch("footer.html")
        .then(response => response.text())
        .then(content => {
            document.getElementById("footer-placeholder").innerHTML = content;
        });
    </script>
</body>
</html>

Note: Some elements like navbar animation (mobile layout) may not work

Last updated