maks maks - 1 month ago 5
CSS Question

Set the child's width relative to parent with presence of margin

I want to set the width of a

header
realtive to
conatiner
width with taking into account
header
's margin



div.container {
width: 100%;
height: 300px;
border: 1px solid red;
position:relative;
}

header{
width: 100%;
border: 1px solid green;
height: 20px;
margin: 10px;
}

<div class="container">
<header></header>
</div>





but
header
element gets out from the border of container on a few pixels on the right side.

Also tried to add
box-sizing: border-box;
to
header
's style, nothing happened. Why?

Answer

Set width: calc(100% - 22px);for header. That's 100% minus twice the border (2 * 1px) minus twice the margin (2*10px), adding up to 22px.

div.container {
  width:  100%;
  height: 300px;
  border: 1px solid red;
  position:relative;
}
    
header{
  width: calc(100% - 22px); 
  border: 1px solid green; 
  height: 20px;
  margin: 10px;
}
<div class="container">
  <header></header>
</div>

Comments