If I set the size of a child element in percentage, the size will be calculated relative to parent\'s content-box, independently from the fact that I have set its box-sizi
The width
property is explicitly defined as being relative to the content box and box-sizing
on the parent doesn't alter this however there is a trick available. What you need is a border that doesn't consume any space and thankfully that is exactly what the outline
property does.
There is one catch: The outline defaults to being outside the content box. Not to worry though because one of outline
's related properties outline-offset
accepts negative values which will bring our outline inside our content box!
HTML
TEST
CSS
.outer {
position: relative;
width: 100px;
height: 100px;
outline:20px solid red;
border:1px solid black;
outline-offset: -20px;
}
.inner {
width: 50%;
height: 100%;
outline:1px solid yellow;
position: absolute; /* required so inner is drawn _above_ the outer outline */
background-color: blue;
}
JS Bin: http://jsbin.com/efUBOsU/1/
With regards to your "bonus question" percentage widths are based on the container size, not the element size. This is true for width
, padding
and margin
. You're getting a padding of 68px because the container is is 680px. This may seem odd but it comes in very handy when you have a rule like {width: 80%; padding: 10%;}
because it guarantees your total object dimensions will be 100% of the container and not some arbitrary value based on your child elements' content.
Note: In future please ask additional questions seperately, especially when they are only marginally related to your primary question.