简体   繁体   中英

Can't text-align:center on css

I can't seem to get my "Home" buttons to the center. The home text is at the left instead of the center.I have my htm and css linked like this: html:

  <html>
  <head>
  <link rel="stylesheet" type="text/css" href="background.css"/>
  </head>
  <body>
  <h1>Bully-Free Zone</h1>
  <h2>"Online harassment has an off-line impact"</h2>
  <a href="New.html" class="nav-link">Home</a>
  </body>
  </html>

Css:

a.nav-link:link
{
color: black;
text-decoration: underline;
font-family:broadway;
font-size:30px;
text-align:center;
}
a.nav-link:visited
{
color: black;
text-decoration: none;
}
a.nav-link:hover
{
color: black;
text-decoration: none;
}
a.nav-link:active
{
color: black;
text-decoration: none;
}

You could wrap it in a div :

<div align="center">
  <a href="New.html" class="nav-link">Home</a>
</div>

Or you can create a class for the div :

HTML:

<div class="myDiv">
  <a href="New.html" class="nav-link">Home</a>
</div>

CSS:

.myDiv {
    text-align: center;
    width: 300px;
}

The text-align property will only center the text within the container it's in. In this case, the a tag is only as wide as the text. So regardless how you set your text-align property on that link tag, it will always appear the same. To center it you need to put it in an element that is wider.

<div id="nav">
    <a href="New.html" class="nav-link>Home</a>
</div>

and your css:

#nav
{
   text-align: center;
}

Good Luck!

属性 text-align:center 应该附属于父元素

<a href="#">Link</a>

a {
  display: block;
  margin: auto;
}

I reply 8 months late but I had the same problem as Backtrack and by trying a combination of the above answers I managed to fix my mishap this way. I share it very respectfully with you, in case someone needs this solution in the future.

CSS:

a {

  text-align: center;

  margin: 20px;

  display: block;

   }

It also works if you use an "Id" in the "a" tag.

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