Martin
Martin

Reputation: 384

How can I center my menu in the middle?

I want to display a CSS horizontal menu in the middle of the header element and make sure that it stays in the middle when resizing the browser window. I of course tried margin: auto;, but it also did not work for me.

jsfiddle code

header .center {
  background: url(../images/header-center.png) no-repeat;
  width: 510px;
  height: 100%;
  /*margin: auto;*/
}

Upvotes: 3

Views: 103

Answers (2)

San
San

Reputation: 1247

here you go

header .center {background: url("https://dl.dropbox.com/sh/1mp20mw7izrycq2/fUbLOQUbN0/pingdom-theme/images/header-center.png") no-repeat; width: 510px; height: 100%; margin: 0 auto;}

#navigation {width: 705px;height: 50px; left: 50%; overflow: visible; margin-left: -255px;}

this should always be half of the parent container width 510px

Upvotes: -1

sulfureous
sulfureous

Reputation: 1526

Beyond the margin: 0 auto; you need to also change the #navigation by removing the position: absolute; and the left: 260px;

Please also notice that you are giving a bigger size to the menu #navigation and a smaller size to the header that contains it with the .center class.

Complete fix to your issue:

header .center {
  background: url("https://dl.dropbox.com/sh/1mp20mw7izrycq2/fUbLOQUbN0/pingdom-theme/images/header-center.png") no-repeat;
  width: 510px;
  height: 100%;
  margin: 0 auto;
}

#navigation {
  width: 705px;
  height: 50px;
  overflow: visible;
}

The reason your code was not working is because you were just doing margin: auto which should technically work because it's giving your: top, right, bottom and left sides a margin of auto and while this is all fine, your #navigation still has the position properties which are not letting you center it.

So just as a final lesson:

Everytime you declar something like margin , padding , border etc... you can do two types of shorthand notation to them to take care of all the sides.

margin: 0 auto means: Margin top and bottom 0 and margin left and right auto.

Upvotes: 4

Related Questions