简体   繁体   中英

Prevent padding from causing element to overflow its parent

Here is my HTML structure:

 .parent{ background-color:#f7f7f7; width: 100px; height: 100px; border:2px solid; } .child{ height: 100%; width: 100%; background-color:#cf5; padding: 15px; } 
 <div class="parent"> <div class="child">something</div> </div> 

As you see div.child goes out of div.parent . That's because of padding: 15px; . Well, how can I calculate this in CSS:

.child{
    height: (100% - the number of padding);
    width: (100% - the number of padding);
}

So this is expected result: (noted that there also should be padding: 15px )

在此输入图像描述

Just add box-sizing: border-box to the child element.

 .parent { background-color: #f7f7f7; width: 100px; height: 100px; border: 2px solid; } .child { height: 100%; width: 100%; background-color: #cf5; padding: 15px; box-sizing: border-box; /* NEW */ } 
 <div class="parent"> <div class="child">something</div> </div> 

The CSS box-sizing property has an initial value of content-box . This means the box model calculates total width by adding the content plus padding plus borders. The calculation is similar for height.

With border-box , the box model includes padding and borders in the width / height calculation.

(Note that margins are always outside the calculation; they will be appended whether in content-box or border-box .)


A second possibility (arguably less efficient than box-sizing ) would be the CSS calc function :

 .parent { background-color: #f7f7f7; width: 100px; height: 100px; border: 2px solid; } .child { height: calc(100% - 30px); /* NEW */ width: calc(100% - 30px); /* NEW */ background-color: #cf5; padding: 15px; } 
 <div class="parent"> <div class="child">something</div> </div> 

Use a margin instead:

.child{
  height: 100%;
  width: 100%;
  background-color:#cf5;
  margin: 15px;
}

Just set the width, height, and margin in the child class. The parent class is just the wrapper it only needs styles that are specific to it. ie The background color and the border.

.parent{
  background-color:#f7f7f7;
  border:2px solid;
}

.child{
  height: 100px;
  width: 100px;
  background-color:#cf5;
  padding: 15px;
}

The child class pushes out of the parent because you set its dimensions to be fixed and the child to 100% of that. You then set the padding which push the child out of the parent.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM