Probosckie
Probosckie

Reputation: 1812

Inheritance of length based css properties in rem unit from root html element

I know that the rem css unit is a relative unit which is used to derive font sizes from the root element i.e html.

My question is- how are length based css properties like width, height, padding, margin, if specified in rem - for any element derived from the html element.

As an example:

<html class="basicStyle">
<body> 
<div id="view">This is some content</div>
</body>
</html>

Style:

.basicStyle{width:500px; font-size:20px}
#view{width:3rem; font-size:2rem}

If I try this out in chrome, the width of the #view div should be 3*500px = 1500px - However it is not so.

I want to know if we specify the width or padding of an element in rem - from which element and how is it calculated - to get the computed width.

Any documentation is welcome too.

Thanks.

Upvotes: 1

Views: 916

Answers (1)

Hidden Hobbes
Hidden Hobbes

Reputation: 14173

The rem unit is equal to the value of the font-size on the root element:

rem unit
Equal to the computed value of font-size on the root element. When specified on the font-size property of the root element, the rem units refer to the property’s initial value.

Font-relative lengths: the em, ex, ch, rem units (http://www.w3.org/TR/css3-values/#font-relative-lengths)

In this case the rem unit will be equal to 20px as this is the font-size set in .basicStyle.

If you use rem to compute the width of an element it will not be based on the width of the root element but the font-size. In your example #view will therefore have a resultant width of 3 * 20 = 60px.

html {
  font-size: 20px;
  width: 500px;
}
#view {
  width: 3rem;
}
<div id="view">This is some content. If you inspect it the width will be 60px.</div>

Upvotes: 1

Related Questions