Why isn't padding or margin working properly in React?

Viewed 24

I'm trying to create a padding or margin around a component, but when I go to apply it, it causes the app to go off screen. Basically, the top and left padding/margin pushes the right side off screen as if it's doing padding + width + padding, instead of working within the set width/height. It doesn't matter if I use margin or padding, the same thing happens with each.

export default () => {

  return (
    <div style={{width: 900, height: 600, background: "green", padding: 20}}></div>
  );
}   

In the picture below, the dark green is the size of the component with padding: 0, and the light green is how it extends if padding: 20.

This is the complete opposite of how I understand padding should work --- the width and height should stay the same, but the interior contents (e.g. text, other components) should have a smaller field to work with.

enter image description here

It doesn't matter if I do this on the root component or on other, interior components. The same thing happens with each. How can I get the width/height of the component to stay constant while using padding?

1 Answers

This is down to the way CSS works. You create the size and then padding and margin get added on afterwards by default. You can change this behaviour using 'box-sizing'. Try this:

const MyElement = () => {
  return (
    <div style={{width: 900, height: 600, background: "green", padding: 20, boxSizing: "border-box"}}></div>
  );
}

For more information about box-sizing see this - https://css-tricks.com/box-sizing/

Related