Search code examples
htmlcsscenter

Centering a div container which is next to a second div container?


I've a div container which is named headline. In this div there are two elements, a menu bar of type unordered list and a div container. I'll centering horizontally the menu bar, the other div container should dock on the right display side with a margin of 5%. How I can do this, has someone an idea?

Okay here is my litte example from jsfiddle: http://jsfiddle.net/nchm3gyj/

HTML

<div class="headline">
        <ul class="navbar">
            <li><a href="#">Home</a></li>
            <li><a href="#">Team</a></li>
            <li><a href="#">Info</a></li>
            <li><a href="#">Downloads</a></li>
        </ul>

        <img class="facebook" src="" />
</div>

CSS

* {
  margin: 0px;
  padding: 0px;
}

.headline {
  height: 60px;
  width: 100%;
  background-color: black;
  margin-top: 10px;
}

.headline .navbar{
  margin: 0px;
  padding: 0px;

  padding-left: 10px;
  padding-right: 10px;

  float: left;
  height: 60px;
  width: auto;
  background-color: yellow;
  list-style: none;
}

.headline .navbar li{
  display: inline;
} 

.headline .navbar li a {
  text-decoration: none;
  line-height: 60px;
  padding-left: 10px;
  padding-right: 10px;
}

.headline .facebook {
  width: 60px;
  height: 60px;
  margin-right: 5%;
  float: right;
}


#clear {
  clear: both;
}

Solution

  • If you want your navigation bar centered in the parent block, here is one way of doing it.

    Apply display: inline-block to the .navbar and text-align: center to .headline.

    Assuming that you want the navigation bar centered with respect to the full width of the parent block, you need to take the image out of the content flow. You can do this by applying position: absolute to the .facebook element.

    .headline {
      height: 60px;
      width: 100%;
      background-color: black;
      margin-top: 10px;
      text-align: center;
      position: relative;
    }
    
    .headline .navbar{
      margin: 0px;
      padding: 0px;
    
      padding-left: 10px;
      padding-right: 10px;
    
      height: 60px;
      width: auto;
      display: inline-block;
      background-color: yellow;
      list-style: none;
    }
    
    .headline .navbar li{
      display: inline;
    } 
    
    .headline .navbar li a {
      text-decoration: none;
      line-height: 60px;
      padding-left: 10px;
      padding-right: 10px;
    }
    
    .headline .facebook {
      position: absolute;
      top: 0;
      right: 5%;
      width: 60px;
      height: 60px;
    }
    <div class="headline">
            <ul class="navbar">
                <li><a href="#">Home</a></li>
                <li><a href="#">Team</a></li>
                <li><a href="#">Info</a></li>
                <li><a href="#">Downloads</a></li>
            </ul>
    
            <img class="facebook" src="http://placehold.it/60x60" />
    </div>