How to center a link using CSS

In this article, you will learn how to center a hyperlink using CSS.

As you might know, the anchor tags <a> have an “inline” display property. So centering a hyperlink isn’t as simple as adding “text-align:center” to the anchor tags.

For all examples that follow, imagine we have the following anchor tag:

<a href="#">A random link</a>

Which looks like:

A random link

Table of contents

Place the HTML link inside of a div. In the styles for the div, apply text-align:center and make the anchor tag an inline-block (display:inline-block).

i.e

<div style="text-align:center">
    <a href="#" style="display:inline-block">A random link</a>
</div>

Results:

A random link

Place the link inside of a div. In the styles, apply “display:flex” and “justify-content:center” to the div.

<div style="display:flex; justify-content:center">
    <a href="#">A random link</a>             
</div>

Results:

A random link

Very similar to flex, place the link inside of a div. In the styles, apply “display:grid” and “justify-content:center” to the div.

<div style="display:grid; justify-content:center">
    <a href="#">A random link</a>             
</div>

Results:

A random link

To center a hyperlink vertically and horizontally, you can continue using either flex or grid.

In the examples below, I set a background-color and a height on the div so that you can see the link centered vertically and horizontally.

Flex

To center the anchor tag with flex. Add these properties to the div: display:flex; justify-content:center; align-items:center. The code would look like:

<div style="height: 100px; background-color:#CDCDCD; display:flex; justify-content:center; align-items:center">
    <a href="#">A random link</a>             
</div>

Result:

A random link

Grid

Similarly, to center the link with grid, add these properties to the div: display:grid; justify-content:center; align-items:center. the code would look like:

<div style="height: 100px; background-color:#CDCDCD; display:grid; justify-content:center; align-items:center">
    <a href="#">A random link</a>             
</div>

Result:

A random link

Technically, to center a hyperlink, you can set its display property to block and apply text-align:center. The problem with this is that the link will span the entire line it’s in.

I will demonstrate what I mean by adding a background color to the link:

<a href="#" style="display:block; text-align:center; background-color:#CDCDCD">A random link</a>  

Result:

A random link

As you can see, the entire width is taken. In contrast, the methods I showed you above, if you apply a background color to, would look like:

A random link

Summary

You now know how to center an HTML link (anchor tags) with CSS. All 3 methods accomplish the same thing, so choose any.

Want to learn how to code and make money online? Check out CodingPhase (referral link)