Sizing a child element relative to parent's border-box

前提是你 提交于 2019-12-03 12:48:28

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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!