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:
- html element with margin: 0, padding: 0
- body element with margin: 0, padding: 10px, border: 2px
- page wrapper element (#page, inside body) with margin: 0, padding: 10px, border: 4px
- header element (inside #page) with margin:0, padding: 20px, border: 2px
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:
- it places it +48 pixels in from the left edge
- adds 100% of the body width (as above)
- then removes 48 pixels from the left edge + 48 pixels from the right edge
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
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.