Writing Nav Bar
Last updated
Last updated
To learn how to add a nav bar, we need to understand a new element: the anchor element!
A property of most websites is having links to other websites. For example, this is a link to the South Brunswick CoderDojo website. Go ahead, click on it! You can see how it opens up the website in a new tab. This is exactly how the anchor element works, and will connect to how we use it in our website.
Similar to the <img>
element, anchor works using an attribute titled href
to provide a link source. Here is how it looks:
Notice how the opening tag has an attribute labeled href
with the actual link included in quotation marks.
The text within the opening and closing tag is the link text
, which is what shows up on screen. For example, this link will appear as Google on your website (where the link text is what is hyperlinked).
The anchor element can also be used to navigate between pages. Suppose this is how the files menu of your website looks like:
If i wanted to link the second page (page_two.html
) in my home page (index.html
), I could do so by the following:
Add links to your secondary or tertiary pages to your homepage to experiment. Show your mentor to verify that you understand how to use the anchor element. Delete the anchors afterwards.
To make a nav bar, we will use the anchor element in combination with an unordered list. Later, we will add another element (the nav
element) to format it better.
Using an unordered list with the anchor element can essentially give us a list of links. These links, as demonstrated above, can link to existing pages in our website and make a makeshift nav bar.
Task:
In your index.html
file, locate the <body>
element. Locate the <header>
element within the body.
Write a new <ul>
element in the <header>
, and nest some <li>
elements within it. If this isn't sounding familiar, see Introduction to HTML.
Add anchor elements that point to your secondary pages to the unordered list. It should look something like this:
Notice how I added the homepage as a list item. It's still necessary to have the homepage in the nav bar, as it allows the user to navigate back home.
The above code snippet uses very generic link text. Use names that are specific and accurately describe the page.
Ask a mentor to confirm you did this section right.
Now, we will be turning our unordered list into a nav bar element. This is important as it will allow us to make it stand out and actually look like a nav bar.
Task:
Before the <ul>
opening tag you added previously, insert a <nav>
opening tag. After the </ul>
closing tag you added previously, insert a </nav>
closing tag.
Highlight the <ul>
element and hit the "tab
" key to indent two spaces past the <nav> tags. It will look something like below:
Copy paste the <nav>
bar code you created above into the <header>
element of each of your sub-pages. This way, viewers of your site will be able to easily access each part.