MrPublic
MrPublic

Reputation: 518

Why do two inline-block elements not remain on the same horizontal line?

After reading up on how to create a horizontal list (Navigation Bar), I wanted to add a header for the current page along with the navigation links on the same line. When viewing the file in a browser, the header and horizontal unordered list appear on different lines, even though they both have their display set to inline. What is the cause of this and is there an easy fix?

.header {
    display: block;
    margin: auto;
}
#nav_bar ul li, #nav_bar h1{
    display: inline-block;
    border: 1px solid black;
}
#nav_bar a:link, #navbar a:visited {
    color: black;
}
<!DOCTYPE html>
<html>
  <head>
    <title>myWebpage</title>
    <link rel="stylesheet" type="text/css" href="index.css">
  </head>
  <body>
   <a href="http://example.com/"><img src="example.jpg" class="header" /></a>
    <div id="nav_bar">
      <h1>Home</h1>
      <ul>
        <li><a href="index.html">Home</a></li>
        <li><a href="foo.html">Foo</a></li>
        <li><a href="bar.html">Bar</a></li>
        <li><a href="baz.html">Baz</a></li>
      </ul>
    </div>
  </body>
</html>

Upvotes: 0

Views: 143

Answers (3)

Antony
Antony

Reputation: 1273

You would need to add a float and a margin for them to align correctly.

#nav_bar ul li, #nav_bar h1{
float: left;
margin: 1px;
display: inline;
border: 1px solid black;
}

Upvotes: 0

Andy Furniss
Andy Furniss

Reputation: 3914

Your ul is not set to inline-block. By default ul is a block level element so you just need to add display:inline-block to your ul too.

Upvotes: 2

isherwood
isherwood

Reputation: 61063

If you inspect the document you see that your list is not inline-block.

.header {
    display: block;
    margin: auto;
}
#nav_bar ul, #nav_bar ul li, #nav_bar h1 { /* <-------------- this */
    display: inline-block;
    border: 1px solid black;
}
#nav_bar a:link, #navbar a:visited {
    color: black;
}
<!DOCTYPE html>
<html>
  <head>
    <title>myWebpage</title>
    <link rel="stylesheet" type="text/css" href="index.css">
  </head>
  <body>
   <a href="http://example.com/"><img src="http://lorempixel.com/200/80" class="header" /></a>
    <div id="nav_bar">
      <h1>Home</h1>
      <ul>
        <li><a href="index.html">Home</a></li>
        <li><a href="foo.html">Foo</a></li>
        <li><a href="bar.html">Bar</a></li>
        <li><a href="baz.html">Baz</a></li>
      </ul>
    </div>
  </body>
</html>

Upvotes: 1

Related Questions