Reputation: 111
By trial and error, I calculated the width of a header block:
width: calc(100% - 96px);
width: calc(100vw - 112px);
Both (seem to) produce the same result. I read how width is defined and want to check that I understand this. I have:
With the % calculation, I subtracted 2 x (total of the above padding and borders).
The result places my header exactly as I would like: centered inside the parent #page wrapper, extending from the left to right edges within the padding. This is because:
Am I correct in this?
Secondly, for the vw calculation, why do I need to subtract an extra 16 pixels?
My question isn't so much the viewport width itself (I don't know JS yet, but I read how to get the viewport widths). The calculation works on different browsers/devices.
The full code is on CodePen: https://codepen.io/necrohell/pen/rNYBepm?editors=0100
Upvotes: 1
Views: 627
Reputation: 2311
Body width cut => (10px X 2)padding + (2px X 2)border = 24px
#page container cut => (10px X 2)padding + (4px X 2)border = 28px
Total = 52px + header's own padding and border (20px X 2 + 2px X 2 = 44)
= 96px (total)
I think you missed header's own padding and border. When "box-sizing" property of the container element is not "border-box" then padding and border are excluded from the width.
Secondly, for the vw calculation, that extra 16 pixels is because of the scrollbar as the scrollbar is included in the 100vw.
Upvotes: 0
Reputation: 943
vw - Relative to 1% of the width of the viewport*
% - Relative to the parent element
* Viewport = the browser window size. If the viewport is 50cm wide, 1vw = 0.5cm.
https://www.w3schools.com/cssref/css_units.php
If you have a parent element with a set width of 300px, using "100%" will have a max width of 300px. Whereas if you use "vw", it goes off the size of the screen. The layout will drastically change from screen to screen and devices. Open your code from your phone to see the change I mean.
Upvotes: -1