0
 <style>
      .parent {
        width: 300px;
        height: 300px;
        border: 1px solid red;
        padding: 20px;
      }
      .child {
        box-sizing: border-box;
        margin: 20px;
        width: 100%;
        height: 100%;
        border: 1px solid blue;
      }
    </style>
  </head>

  <body>
    <div id="app">
      <div class="parent">
        <div class="child"></div>
      </div>
    </div>
  </body>

I have a child div nested inside parent div which has a padding attribute. Child div has a margin attribute as well. I expected child div to be in the center like the image below.

enter image description here

however, when I run code, child div is skewed to the right bottom.

enter image description here

I set box-sizing attribute to border-box to calculate margin: 20px into the final width and height yet the result is the same. my question is 1)how do I center child div with margin applied 2)why border-box does not have any effects on child div?

D Park
  • 504
  • 10
  • 19

2 Answers2

1

Just remove margin and it will work. You have an explanation here in the answer: Flex items not respecting margins and box-sizing: border-box.

Keep in mind that box-sizing: border-box brings padding and borders into the width / height calculation, but not margins. Margins are always calculated separately.

.parent {
        width: 300px;
        height: 300px;
        border: 1px solid red;
        padding: 20px;
      }
      .child {
        box-sizing: border-box;
        width: 100%;
        height: 100%;
        border: 1px solid blue;
      }
      
<body>
    <div id="app">
      <div class="parent">
        <div class="child"></div>
      </div>
    </div>
  </body>
  
  
  
Filip Huhta
  • 2,043
  • 7
  • 25
  • Thanks for your comment, but adding padding to the child div won't do anything to itself though. Also my question is about why child div is not centered when margin is applied. – D Park Apr 21 '21 at 05:25
-1

If you want to make it center you should remove margin from child div as the margin is outside of child div and is pushing the child div to the left

This should work

 <body>
    <style>
      .parent {
        width: 300px;
        height: 300px;
        border: 1px solid red;
        padding: 20px;
      }
      .child {
        box-sizing: border-box;
        width: 100%;
        height: 100%;
        border: 1px solid blue;
      }
    </style>

    <div id="app">
      <div class="parent">
        <div class="child"></div>
      </div>
    </div>
  </body>

You can also do this on parent div to center almost anything

        /* display: flex;
        align-items: center;
        justify-content: center; */