Conlan Ryan
Conlan Ryan

Reputation: 59

How to center a link in CSS?

I have tried:

This is my code:

HTML:

<a id="final" href="sooce2.html"></a>

CSS:

#final {
   text-align: center;
}

Upvotes: 2

Views: 18431

Answers (5)

cocobeans
cocobeans

Reputation: 101

Make sure no assignments that take precedence in the hierarchy are overriding it. margin-left: auto; and margin-right: auto; should work. None of the above solutions worked for my test error reproduction but those did.

If that still doesn't work, my default is always flexbox. It never fails me. Use display: flex; justify-content: flex-end;. To learn more about flexbox, visit this website: https://css-tricks.com/snippets/css/a-guide-to-flexbox/.

Upvotes: 0

Blackmagyk
Blackmagyk

Reputation: 80

You can just do this:

.center-text {
  text-align: center;
  display: block;
}
<div class="center-text">
<a id="finall" href="sooce2.html">Link goes here</a>
</div>

Upvotes: 2

Tyler Fowle
Tyler Fowle

Reputation: 569

anchor tags are an inline level element, therefore the things you have tried will not work.

either setting a { display: block; } with text-align: center;

or applying text-align: center; to its parent

.center-text {
  text-align: center;
}

a.center-text {
  display: block;
}
<div class="center-text">
<a href="#">Link goes here</a>
</div>


<a href="#" class="center-text">Link goes here</a>

Upvotes: 5

samo0ha
samo0ha

Reputation: 3796

wrap it inside a p element and assign the text-align:center; to the p element.

<p>
    <a id="final" href="sooce2.html"></a>
</p>

CSS

p {
   text-align: center;
}

Upvotes: 0

Kresimir Pendic
Kresimir Pendic

Reputation: 3614

By default a anchor elemenet is inline element and does not have defined width .. so you can make text inside centered if you either spefify it's width explicitly like XX px, or like my example where ) make it block element, and block elements default to be full width of it's parent.

a{
  display: block;
  text-align: center;
}
<a href="#">My link</a>

Upvotes: 2

Related Questions