2

Please take a look at https://jsbin.com/jodorazone/1/edit?html,css,output

If I set parent to display: block, only the padding of the children is taken into account. If set to display: flex, child is rendered along with padding inside the parent's padding.

Why does it behave like this?

1
  • 1
    box-sizing: border-box is the reason, check f23 console.log Commented Jan 8, 2019 at 8:43

1 Answer 1

1

It's because span is an inline element by default and padding top/bottom will not affect the height. If you want to set padding, just set span display: block. Reference: https://www.w3.org/TR/CSS2/visudet.html#inline-non-replaced

body {
  margin: unset;
}

button, div {
  display: block; 
  width: 100%;
  justify-content: center;
  align-items: center;
  padding: 12px;
  border: 1px solid black;
}

button span,
div span {
  /* if button, div is set to display: block, their (parent) padding isn't factored in */
  padding: 10px;
  display: block;
}
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
<div><span>div</span></div>
  <button><span>button</span></button>
</body>
</html>

About display: flex behaviour:

The display value of a flex item is blockified: if the specified display of an in-flow child of an element generating a flex container is an inline-level value, it computes to its block-level equivalent. (See CSS2.1§9.7 [CSS21] and CSS Display [CSS3-DISPLAY] for details on this type of display value conversion.)

Reference: https://www.w3.org/TR/css-flexbox-1/#flex-containers

Sign up to request clarification or add additional context in comments.

5 Comments

to be more precise the issue is only with the top/bottom padding
@TemaniAfif thanks, I have updated the answer, do you have any reference about this issue?
w3.org/TR/CSS2/visudet.html#inline-non-replaced (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)
and it's not about won't work but will not affect the height as padding-top/bottom works fine (add a background and you will see the effect)
"The display value of a flex item is blockified" - this is the kind of justification I was looking for :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.