Rajit s rajan Rajit s rajan - 1 year ago 59
HTML Question

HTML: Text:align property working with span or with a tag

I tried the below code wherein I wanted to center a link , I dont know why these 2 below piece of code didnt work


<span class="my-class">
<a href="http://www.example.com">example</a>​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​


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

The piece of code which worked was:
<div class="my-class">
<a href="http://www.example.com">example</a>​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​

Could you please tell me why the above 2 codes didnt work?

Answer Source

The first doesn't because the anchor a is inside an inline element, which just grow to its content's size, and their parent, the body, does not have the property text-align: center set.

The second doesn't because its parent, in this case the body, need to have the rule text-align: center

The third does because the my-class most likely has the text-align property set to center, and as a div is a block element it spawn the full width of its parent, in this case the body, hence the anchor will center inside it.

So, to center an inline (and inline-block) element, its parent need the propertytext-align: center set, and to center a block element, like a div, it has to have a width, less wide than its parent, and its margin's left/right set to auto.


.centered-span {
  text-align: center;

.centered-div {
  width: 50%;
  margin: 0 auto;
<span class="centered-span">Hey there (not centered)</span>

<div class="centered-span">
  <span>Hey there - span</span>
<div class="centered-div">Hey there - div</div>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download