Question: 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?

Answer: 
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 property`text-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

```css
.centered-span {
  text-align: center;
}

.centered-div {
  width: 50%;
  margin: 0 auto;
}
```

```html
<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>
```
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.