Reputation: 48
I’m working on a project and I want my webpage to maintain its style and aspect ratio anytime it is resized or viewed on any device. I have tried to use the position attribute (position:fixed;) on CSS but it’s not working. How can this be done using CSS?
Upvotes: 0
Views: 1505
Reputation: 297
figure {
width: 36%;
margin: 8px auto;
}
div.relative_div {
width: 100%;
padding-bottom: 56.25%; /* 16:9 */
position: relative;
background: black;
}
div.relative_div > div {
position: absolute;
top: 0; bottom: 0; left: 0; right: 0;
color: white;
font-size: 24px;
text-align: center;
}
<html>
<body>
<figure>
<div class="relative_div">
<div>Relative Aspect Ratio </div>
</div>
</figure>
</body>
</html>
As you can see in the CSS, all we have to do is nest an element with 100% width inside a “responsive” percentage-based-width parent element, and then declare a % for bottom or top padding based on the ratio we want to maintain. To calculate the percentage needed for any aspect ratio we can use the following formula:
B / (A / 100) = C%
So for 16:9 (where 16 is A and 9 is B):
9 / .16 = 56.25 (%)
Upvotes: 2