How do I center an anchor element in CSS?

I just want to have my anchor in the middle of the screen horizontally, how might I do this?

<a href="http://www.example.com">example</a>

Solution 1:

Add the text-align css property to its parent style attribute

Eg:

<div style="text-align:center">
  <a href="http://www.example.com">example</a>​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​
</div>​

Or using a class (recommended)

<div class="my-class">
  <a href="http://www.example.com">example</a>​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​
</div>​
.my-class {
  text-align: center;
}

See below working example:

.my-class {
  text-align: center;
  background:green;
  width:400px;
  padding:15px; 
}
.my-class a{text-decoration:none; color:#fff;}
<!--EXAMPLE-ONE-->
<div style="text-align:center; border:solid 1px #000; padding:15px;">
  <a href="http://www.example.com">example</a>​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​
</div>​

<!--EXAMPLE-TWO-->
<div class="my-class">
  <a href="http://www.example.com">example</a>​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​
</div>​

Q: Why doesn't the text-align style get applied to the a element instead of the div?

A: The text-align style describes how inline content is aligned within a block element. In this case the div is an block element and it's inline content is the a. To further explore this consider how little sense it would make to apply the text-align style to the a element when it is accompanied by more text

<div>
  Plain text is inline content. 
  <a href="http://www.example.com" style="text-align: center">example</a> 
  <span>Spans are also inline content</span>
</div>

Even though threre are line breaks here all the contents of div are inline content and therefore will produce something like:

Plain text is inline content. example Spans are also inline content

It doesnt' make much sense as to how "example" in this case would be displayed if the text-align property were to be applied it it.

Solution 2:

write like this:

<div class="parent">
 <a href="http://www.example.com">example</a>
</div>

CSS

.parent{
  text-align:center
}

Solution 3:

Two options, that have different uses:

HTML:

<a class="example" href="http://www.example.com">example</a>

CSS:

.example { text-align: center; }

Or:

.example { display:block; width:100px; margin:0 auto;}

Solution 4:

Try

margin: 0 auto;
display:table

Hope that helps somebody out.

Solution 5:

try to wrap a div around and add these styles to the div:

 width: 100%; 
 text-align:center;