Is padding-bottom relative to element's width?

限于喜欢 提交于 2019-12-08 12:04:33

问题


Padding-bottom must be relative to element's width but i tested in last version of Chrome and Firefox and padding-bottom is relative to parent's width.

I need a element relative to element's width but it doesn't work:

width: 200px;
padding-bottom: 50%; /* must be 100px  */
height: 0;

See example: http://dabblet.com/gist/6898263

What can i do?


回答1:


No, in the padding properties, percentages are relative to the width of the containing block, which is here probably the body element or a div element with no width set, so it occupies the available width.

If you wrap the element in a div container and set the desired width on the container, then you can use a percentage as intended.




回答2:


There is no connection between width and padding properties. However, there is a third thing that they both rely on. It's em unit (documentation). Em unit can be used to define all measurable properties (like width, border-width etc.) and it depends on font-size (which should be in that case defined in px).

You can try this simple hack:

font-size: 200px;
width: 1em;
padding-bottom: 0.5em;

See my fiddle: http://jsfiddle.net/Wgzrn/.

In your example you used another div inside with desired font-size defined to 24px so 200px font-size in the parent won't be a problem here.

My solution is not much elegant but I don't know any other.




回答3:


Why you add the padding and the background color to the wrapped div? If I change the css on your gist with the following css, I have a 100px padding. Here the code:

div.aspect-ratio {
  width: 200px;
  height: 0;
  position: relative;
}

div.aspect-ratio > div {
  padding-bottom: 50%; /* must be 100px  */
  position: absolute;
  background: blue;
  color: white;
  font-size: 24px;
  text-align: center;
}


来源:https://stackoverflow.com/questions/19267292/is-padding-bottom-relative-to-elements-width

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