Rajit s rajan
Rajit s rajan

Reputation: 595

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

Code1:

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

Code2:

  <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>​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​
</div>​

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

Upvotes: 1

Views: 38

Answers (3)

Asons
Asons

Reputation: 87262

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.

Sample

.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>
  
<div class="centered-div">Hey there - div</div>

Upvotes: 1

Henrique M.
Henrique M.

Reputation: 502

span and a elements do not behavior as blocking element because they are supposed to be used inline. You either will need to set it by setting up a display and width attribute or wrapping it around a parent. Instead, you could use a ul>li>a hierarchy and set their attributes properly.

.aBox {
  display: block;
  width: 200px;
  text-align: center;
  background-color: lightyellow;
}


.notBox {
  background-color: lightblue;
  text-align: center;
}
<span class="aBox">
  <a href="#">Hey, it's a link</a>
</span>

<span class="notBox">
  <a href="#">Hey, it's a link</a>
</span>

Upvotes: 1

Dominofoe
Dominofoe

Reputation: 603

A span element is an in-line element which is only as wide as its content. Whereas a div element is a block level element and will be as wide as the page or its containing div.

When using the `text-align: center;' property, you must place it on the element containing the element that you want to center.

Upvotes: 0

Related Questions