Reputation: 89
When I apply width as a percentage to any inner element of a page, it applies the percentage to the width of its parent container.
How to specify width of any inner element as a percentage of width of Body, instead of the default(percentage of width of parent container)?
Additional Information: Depending on the device, the width of the Body will change. For devices above 1440px, it will have width as 1440px, else if width of device is less, then width of body will be 100%.
Upvotes: 2
Views: 2206
Reputation: 979
You shouldn't stylize your <body>
.
Instead add a wrapper with a combo of view port units and max-width.
.container {
width: 100vw;
max-width: 1440px;
height: 100vh;
margin: 0 auto;
background-color: green;
}
<div class="container"></div>
Upvotes: 2
Reputation: 1307
You can use viewport units.
<div class="parent"> /** Width:900px; **/
<div class="inner"> /** 100% of BODY, not of parent div **/
</div>
</div>
<style>
.parent {
background:red;
width:20px;
padding: 10px;
}
.inner {
background:green;
width: 100vw;
}
</style>
or
you can get width of the body using javascript and set its percent of width to other elements
get width of body:
document.body.clientHeight;
set width in html element:
document.getElementById('div_register').setAttribute("style","width:500px");
Upvotes: 2
Reputation: 7324
If you always want the width to be the width of the body then you can use viewport units.
1 vw is always 1% of the width of the viewport's initial containing block, which is usually the body.
So if you want something to be 20% of the body, you set it's width to width: 20vw
.
Should work regardless of how far down in the DOM you nest this, and it works relative to whatever the screen size is when the page renders.
More on viewport units here https://css-tricks.com/fun-viewport-units/
Upvotes: 1