Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does <span> break outside <div> when margin and padding is applied?

Tags:

html

css

I know this is very basic CSS. How do I keep the span contained within the div? At the moment, the span extends outside the top and bottom of the div.

div {
  width: 200px;
  margin: 10px;
  background-color: #ff0;
}
span {
  margin: 5px;
  padding: 5px;
  background-color: #fc0;
}
<body>
  <div>
    <span>span</span>
  </div>
</body>
like image 328
user1405195 Avatar asked May 19 '12 14:05

user1405195


People also ask

Can we apply margin and padding to span?

The reason vertical padding /margin does not work with spans is that it's an inline element.

Does padding work on span?

span won't have padding because it is an inline element by default, so set inline-block or block.

Why is my content out of the div?

This problem basically occurs when the height and width of DIV element are small such that all the text can not be fitted in that DIv.

Can span element have margin?

The <span> tag is a inline element, it fits into the flow of the content and can be distributed over multiple lines. We can not specify a height or width or surround it with a margin. It can be placed inside a paragraph to define a part of it without affecting the appearance of the text.


2 Answers

To answer your question, this isn't just an issue with padding or margin, but also with width, display, and the box model.

jsFiddle

span {
    display: inline-block;
}

This will honor any padding, margins, or widths you apply to the span.

like image 88
gmeben Avatar answered Oct 04 '22 21:10

gmeben


Inline elements will not consume vertical padding and margin space. You can make the span display: block, but without more detail I don't know if that will achieve your goal.

like image 35
Matthew Avatar answered Oct 04 '22 22:10

Matthew