0

When I use a css class within a div tag it seems to ignore what is inside the css.

.centered {
  background-color: red;
  padding: 5px 20px 5px 20px;
}
<div style="text-align:center" class="centered">
    I am centered with bg around me
</div>

When is use the same class with a span tag nested within the div element it does what I want.

<div style="text-align:center">
    <span class="centered">I am centered with bg around me</span>
</div>

Why is this? What makes the difference?

This is with the first code
This is with the second

Nope
  • 22,147
  • 7
  • 47
  • 72
Ryepower
  • 151
  • 1
  • 1
  • 7

2 Answers2

0

Its because a span is a inline element and a div is a block element.

To see the difference you can make the span a block element by doing this:

.centered {
  display: block
}

More about inline vs block

Dizza
  • 102
  • 1
  • 2
  • 8
0

<div /> is a block level element, which takes up 100 % of the available width by default. <span /> is an inline element, which only takes up the minimum amount of width it needs to display its content.

There's a really good article on learnlayout.com that does a great job explaining this.

Happy coding :)

Kris Selbekk
  • 7,438
  • 7
  • 46
  • 73