Sizing a child element relative to parent's bo

2019-03-25 20:12发布

问题:

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-sizing property to border-box.

So if I have something like this:

.parent {
  box-sizing: border-box;
  padding: 0 100px;
  width: 600px;
}

.child {
  width: 50%;
}

The width of .child will be 50% of 400px (parent's width after padding has been applied). You can see an example here: JSBin

Main Question

Is there a way to make the width of a child element relative to the parent's border-box rather than the parent's content-box?

Bonus question

While making my example I noticed a weird behavior in the calculation of the size. Setting the .parent's padding as 0 10% actually gives a padding of 68-odd pixels from each side. Why is that? Isn't 10% of 600px 60px or I am missing something?

回答1:

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

<!DOCTYPE html>
<html>
<head></head>
<body>
  <div class="outer">
      <div class="inner">
      TEST
      </div>
  </div>
</body>
</html>

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.



标签: sizing css