Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to apply this sidebar to all pages using CSS?

Tags:

html

css

I have 4 different html web pages. The html code below is for a menubar which I want to apply to all four pages. Is there any way I can do this using CSS instead of copying/pasting this menubar html code on all 4 of my html web pages? Basically the four pages are Home, News, Contact, About. Whenever someone clicks on a menubar item, it will redirect them to one of the 4 pages. And on all 4 of those pages, I want the menubar to be displayed. I want to create a CSS file which I can just link all 4 pages to and then the menubar will be displayed (code below). Thanks in advance!

Is there any way I can create a CSS file which at least takes care of the styling? And I will manually add the menubar buttons to each html page?

<!DOCTYPE html>
<html>
<head>
<style>
body {
    margin: 0;
}

ul {
    list-style-type: none;
    margin: 0;
    padding: 0;
    width: 25%;
    background-color: #f1f1f1;
    position: fixed;
    height: 100%;
    overflow: auto;
}

li a {
    display: block;
    color: #000;
    padding: 8px 0 8px 16px;
    text-decoration: none;
}

li a.active {
    background-color: #4CAF50;
    color: white;
}

li a:hover:not(.active) {
    background-color: #555;
    color: white;
}
</style>
</head>
<body>

<ul>
  <li><a class="active" href="page1.html">Home</a></li>
  <li><a href="page2.html">News</a></li>
  <li><a href="page3.html">Contact</a></li>
  <li><a href="page4.html">About</a></li>
</ul>

<div style="margin-left:25%;padding:1px 16px;height:1000px;">

</div>

</body>
</html>
like image 464
javaprogrammer Avatar asked Jan 16 '16 02:01

javaprogrammer


2 Answers

You shouldn't/can't do this with CSS. You need either:

- For a non-programmatic solution: <link rel="import" href="sidebar.html"> save your sidebar in a sidebar.html file and call it with this snippet. Check out the support tables for this function. (Deprecated)

  • Use ES modules: Is there a way to use es6 modules to import html template into javascript?
  • Use a template engine to produce the results you want.
  • Include it with PHP like so: <?php include 'sidebar.php'; ?>

There are more solutions, but these are the most obvious AFAIK.

like image 192
fnune Avatar answered Sep 19 '22 18:09

fnune


You cannot achieve this with HTML and CSS only. If you have PHP server then, I suggest to create a PHP file and put your nav-bar code and then use the following PHP code in the all pages.

<?php include 'nav.php'; ?>

Here is the code for nav.php:

<?php
echo 
'<ul>
  <li><a class="active" href="page1.html">Home</a></li>
  <li><a href="page2.html">News</a></li>
  <li><a href="page3.html">Contact</a></li>
  <li><a href="page4.html">About</a></li>
</ul>';
?>
like image 27
Maihan Nijat Avatar answered Sep 20 '22 18:09

Maihan Nijat