Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to horizontally center a link element with CSS?

Tags:

css

Like the title said, how can I horizontally center the <a> element? Major bonus points for doing it with CSS only.

.center {
  text-align: center;
  align-self: center:
  margin: 0 auto;
}
.expander_link {
  padding-top: 50px;
  padding-bottom: 50px;
  margin: 0 auto;
  font-size: 100%;
  font-weight: bold;
  color: hotpink;
  text-align: center;
  align-self: center;
  text-decoration: none;
}
<h4 class="center">hello</h4>
<p>
  blah blah blah blah blah blah blah blah blah blah
</p>
<a id="link_1" href="3801" data="1" class="expander_link">center me horizontally</a>
like image 628
William Jockusch Avatar asked Dec 11 '22 19:12

William Jockusch


2 Answers

You should try like this-

  .center {
  text-align: center;
  /*align-self: center;*/
  margin: 0 auto;
}
.expander_link {
  padding-top: 50px;
  padding-bottom: 50px;
  margin: 0 auto;
  font-size: 100%;
  font-weight: bold;
  color: hotpink;
  text-align: center;
  align-self: center;
  text-decoration: none;
  display: block;	
}
<h4 class="center">hello</h4>
<p>
  blah blah blah blah blah blah blah blah blah blah
</p>
<a id="link_1" href="3801" data="1" class="expander_link">center me horizontally</a>
like image 55
Mukul Kant Avatar answered Jan 07 '23 11:01

Mukul Kant


To center an inline-level element, like <a>tag, I would suggest to wrap it into a block-level element, like <p> or <div> etc, then set p {text-align:center;}. See the simplest example follows:

p {
  text-align: center;
}
<p><a href="#">Center me horizontally</a></p>

If you want extra spacing around, simply add a {display:inline-block;} and set margin and padding values as needed, or set it on <p> tag.

p {
  text-align: center;
}
p a {
  display: inline-block;
  margin: 50px 0;
  padding: 10px;
  outline: 1px solid aqua;
}
<p><a href="#">Center me horizontally</a></p>

If you are not allowed to modify the markup, you could do the following. Note, the clickable area will be expanded, padding applies to. you might not want that. Run the demo to see.

a {
  display: block;
  text-align: center;
  margin: auto;
  
  padding-top: 50px;
  padding-bottom: 50px;
  outline: 1px solid aqua;
}
<a href="#">Center me horizontally</a>

To fix the unwanted spacing, you could do the display:table hack. It a combination of inline and block (shrink-to-fit and forces line break before/after features).

a {
  display: table;
  margin: 50px auto;
  padding: 10px;
  outline: 1px solid aqua;
}
<a href="#">Center me horizontally</a>

Of course, there are other ways, such as using flexbox, follow the other good answers to learn more about it.

like image 20
Stickers Avatar answered Jan 07 '23 11:01

Stickers