Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I center my menu in the middle?

Tags:

html

css

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;*/
}
like image 965
Martin Avatar asked Nov 29 '25 17:11

Martin


1 Answers

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.

like image 181
sulfureous Avatar answered Dec 01 '25 08:12

sulfureous



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!