简体   繁体   中英

Why won't my nav element go to the center or change style?

I am trying to get my nav element to center but it won't work for the older versions of Internet Explorer or Chrome. It also won't change style. How can I get this to center and change? Here is the code:

The nav:

<nav id="Nav">
    <a href="TMR Library.html">Library</a> |
    <a href="TMR Contact.html">Contact</a> |
    <a href="TMR About.html">About</a>
</nav>

The CSS

#Nav {
    margin:0 auto;
    font-size: 40px;
    color: #22b14c;
    font-family: "Papyrus";
}

There are many ways to centre elements:

Margin way:

With a set width or display: inline-block; you can use:

margin-left: auto;
margin-right: auto;

text-align way:

With a set width or display: inline-block; you can add this to the parent:

text-align: center;

Absolute way:

position: absolute;
left: 50%;
margin-left: width/2;

or

position: absolute;
left: 50%;
transform: translate(0, -50%);

Also don't worry too much about ie7 and below as the the majority of people use higher versions of ie or a different browser though this should work up until ie6

Another thing to watch out for is that you want to use a ul for your navbar. I know, from experience, that it works fine though if you ever want to add a drop-down to the navbar then it is much harder.

Use the below:

text-align: center;

instead of

margin 0 auto;

Sample Fiddle

Note: My assumption was that you did not want to specify a width. Otherwise, you can just use the margin as already stated in the other answers.

EDIT: To use the <nav> and other HTML5 tags with lower version of IE, you can use the HTML5shiv.js (by including the below script).

<script src='http://cdnjs.cloudflare.com/ajax/libs/html5shiv/3.6.2/html5shiv.js' type='text/javascript'></script>

Since it is a block element it will spread 100% across the page, try giving it a width

#Nav {
display:Block;
width:500px;
margin:0 auto;
font-size: 40px;
color: #22b14c;
font-family: "Papyrus";
}

margin: 0 auto; has no meaning without specifying the width.

Use:

  #Nav 
  {
     margin-left:auto;
     margin-right:auto;
     width: 12em;
     font-size: 40px;
     color: #22b14c;
     font-family: "Papyrus";
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM