Dale M. Rollinson
Dale M. Rollinson

Reputation: 21

My css navigation menu refuses to center in the browser?

I've tried all the places to put

margin-right: auto

and

margin-left:auto

The use of

display: inline-block

works brilliantly on the actual links, but otherwise messes with the menu if added as a parent.

I feel that in order to make it center in the browser viewport, that I will need to lose some of the styling. I feel there is a conflict between some aspect of the styling that is preventing the centering.

I hope that I'm wrong, and it is possible with somebody's suggestion(s)...

Kind Regards, Dale

Here is my CSS:

.navigation {
    height: auto
    width: 96%;
    border-top-color: rgb(119,120,122);
    border-top-style: solid;
    border-top-width: 1px;
    border-bottom-color: rgb(119,120,122);
    border-bottom-style: solid;
    border-bottom-width: 1px;
    margin-top: 1%;
    margin-right: auto;
    margin-bottom: 1%;
    margin-left: auto;
    padding-top: 1%;
    padding-bottom: 1%;
    background-color: transparent;
    background-image: none;
}

ul {
    height: auto;
    overflow: hidden;
    margin-right: auto;
    margin-left: auto;
}

ul li {
    display: inline;
}

ul li ul {
    display: none;
}

ul li:hover ul {
    height: auto;
    width: 96%;
    display: block;
    position: absolute;
    margin-right: auto;
    margin-left: auto;
}

ul li a {
    display: inline-block;
    cursor: pointer;
    position: relative;
    margin-right: 0.15%;
    margin-bottom: -0.2%;
    padding-top: 1.25%;
    padding-right: 1.4%;
    padding-bottom: 1.25%;
    padding-left: 1.4%;
}

ul li:hover ul a {
    margin-right: -0.2%;
    margin-bottom: 0;
}

P.S. I took out my comments and any non-essential codes, I realize that I write in long-hand CSS, but I like to do so ;-)

Upvotes: 2

Views: 1154

Answers (2)

andyb
andyb

Reputation: 43823

Simplest way is to add a width to your top level <ul>, for example:

ul {
    height: auto;
    overflow: hidden;
    margin-right: auto;
    margin-left: auto;
    width:80%;
    text-align:center;
}

Edit: Sorry I misread the question, I thought you just wanted the entire menu to not span the entire width of the window, rather than center the menu contents. Added text-align:center; to my answer as @Jacob already suggested.

Upvotes: 1

Jacob
Jacob

Reputation: 78850

The reason why it's not displaying centered is because the ul holding the menu has no width specified; therefore, it's rendering at 100% width; in other words, the left/right margins being at auto have no effect.

Try adding text-align: center to the ul so that the lis, being inline, will be able to be centered.

Upvotes: 4

Related Questions