2

.case1 {
  margin-bottom: 10px;
}
.case2 span {
  margin-bottom: 10px;
}
<div class="case1">
  <span>something</span>
</div>
<div class="case2">
  <span>something</span>
</div>

If apply css as follows, the result you see on the screen is the same. So, which of the two methods is best practice and why?

  • thx answers. If it is a p element and not a span element, the result is likely to be the same. What is the best practice in this case?
newbieeyo
  • 663
  • 4
  • 12

3 Answers3

4

<div>'s and <p>'s for example are Block Level elements that can take up margin on all sides. <span>'s cannot as it's an Inline element that takes up margins horizontally only.

From W3:

Margin properties specify the width of the margin area of a box. The 'margin' shorthand property sets the margin for all four sides while the other margin properties only set their respective side. These properties apply to all elements, but vertical margins will not have any effect on non-replaced inline elements.

You can set display: inline-block; on your span to make it block-level.

.case1 {
  margin-bottom: 10px;
}

.case2 span {
  margin-bottom: 10px;
  margin-top: 20px; /* margin doesn't work */
  color: hotpink;
}

.case3 span {
  display: inline-block; /* made it block-level, margin works */
  margin-top: 40px;
  color: blue;
}
<div class="case1">
  <span>something</span>
</div>


<div class="case2">
  <span>something</span>
</div>

<div class="case3">
  <span>something</span>
</div>
Kameron
  • 10,240
  • 4
  • 13
  • 26
  • thx! could you answer my extra question? – newbieeyo May 24 '22 at 15:10
  • "If it is a p element and not a span element, the result is likely to be the same." this one? It works as expected because it is block-level. https://jsfiddle.net/kameronmayers/q1xby7st/2/ – Kameron May 24 '22 at 15:16
3

In any case you'd prefer to use case 1 because case 2doesn't work if there are other elements in the <div>

p{
  margin: 0px;
  padding: 0px;
}
.case1 {
  margin-bottom: 15px;
}

.case2 span {
  margin-bottom: 15px;
}
<div class="case1">
  <span>something</span>
    <p>
  test
  </p>
</div>

<div class="case2">
  <span>something</span>
  <p>
  test1
  </p>
</div>

<p>
test2
</p>

As you can see there is no separation between test1 and test2 because case2 doesn't affect it. But there's a sepration between test and the something from case 2

Neo
  • 525
  • 3
  • 17
3

By architecture, the styles of the span tag are still children of the parent div and not all children are equal to the parent, a clear example is: If I have a parent div with style color:#333, all the children, including the span ones, will inherit this color. Otherwise, if the child wants another color, be it span or another label, you use the second option. This applies even in margins.