0

I have an inline element nested within another inline element. In this case I am using a b element nested within a label. Now when I give both elements a border, I expect the outer element to fully contain the inner element. But when I apply some padding to the inner element, it ends up sticking out of it's parent. I must admit that after almost 2 decades of HTML/CSS, I still don't understand why this happens. Can anyone here:

  1. Explain why this happens
  2. Propose a fix

I want both borders to align exactly, without having to specify any dimensions on the label.

label {
  border: 1px solid red;
}

b {
  border: 1px solid green;
  padding: 20px;
}
  
<label><b>TEST</b></label>

You might think that label has some magic that causes this, but AFAICT this happens with all inline elements. For example, when using span instead of label, we get the exact same effect:

span {
  border: 1px solid red;
}

b {
  border: 1px solid green;
  padding: 20px;
}
<span><b>TEST</b></span>
Stijn de Witt
  • 40,192
  • 13
  • 79
  • 80
  • inline-block to parent element and the child – Temani Afif Apr 06 '20 at 10:30
  • also, `inline-block` the parent *and* the child is not a very scalable solution. What if I don't know in advance what content will be in my container? Plus I still have no explanation why this happens... I guess I'm just dumb or something. – Stijn de Witt Apr 06 '20 at 10:38
  • don't judge the time of closing a question, judge the duplicate instead. No need to bring the *unwelcome stuff* to justify that I am doing bad and you are a victim. Read the duplicate and if you think it's not suitable to your question, edit to say *why* (I alos close questions in less than 1min ...) – Temani Afif Apr 06 '20 at 10:41
  • Maybe you can explain how the dupe answers my first question of *why* this happens? – Stijn de Witt Apr 06 '20 at 10:43
  • two answers explain this and using link to the Specification and if you check that link you can also read : *The vertical padding, border and margin of an inline, non-replaced box start at the top and bottom of the content area, and has nothing to do with the 'line-height'. But only the 'line-height' is used when calculating the height of the line box.* ... I will add more duplicates, there is more – Temani Afif Apr 06 '20 at 10:53
  • @TemaniAfif The dupe question seems related, I certainly agree. But it is imho not a dupe. I am specifically asking about *nested* inline elements and containment. The dupe is about margin/padding top/bottom on inline elements. Can I beg you to reconsider closing and give my question a chance to get some answers? Please? – Stijn de Witt Apr 06 '20 at 10:55
  • now you have 5 duplicates. The margin behave the same as padding that's why you will find it in the duplicate (the only difference is that backgroud/border won't apply to margin) and nesting inline elements will change nothing to the behavior your are facing. – Temani Afif Apr 06 '20 at 11:05

0 Answers0