Wednesday, October 16, 2013

How to maintain aspect ratio in flexible or responsive layouts using CSS?


Maintain aspect ratio in flexible or responsive layouts using CSS:

body {
 background: #F1F1A8;
 width: 25%;
 margin: 10px auto;
 font-size:63%;
}
div.aspectRatio_4-3,div.aspectRatio_16-9,div.aspectRatio_3-2,div.aspectRatio_8-5{
 width: 100%;
 position: relative; 
}
div.aspectRatio_4-3 { 
 padding-bottom: 75%; /* 4:3 */; 
 background: red; 
}
div.aspectRatio_16-9 { 
 padding-bottom: 56.25%; /* 16:9 */; 
 background: blue; 
}
div.aspectRatio_3-2 { 
 padding-bottom: 66.66%; /* 3:2 */; 
 background: green; 
}
div.aspectRatio_8-5 { 
 padding-bottom: 62.50%; /* 8:5 */; 
 background: orange; 
}
div.aspectRatio_4-3 > div, div.aspectRatio_16-9 > div, div.aspectRatio_3-2 > div, div.aspectRatio_8-5 > div {
 position: absolute;
 top: 0;
 bottom: 0;
 left: 0;
 right: 0;
 color: white;
 font-size: 2.4em;
 text-align: center;
}

Example:

<!DOCTYPE html>
<html>
<head>
<style>
body {
 background: #F1F1A8;
 width: 25%;
 margin: 10px auto;
 font-size:63%;
}
div.aspectRatio_4-3,div.aspectRatio_16-9,div.aspectRatio_3-2,div.aspectRatio_8-5{
 width: 100%;
 position: relative; 
}
div.aspectRatio_4-3 { 
 padding-bottom: 75%; /* 4:3 */; 
 background: red; 
}
div.aspectRatio_16-9 { 
 padding-bottom: 56.25%; /* 16:9 */; 
 background: blue; 
}
div.aspectRatio_3-2 { 
 padding-bottom: 66.66%; /* 3:2 */; 
 background: green; 
}
div.aspectRatio_8-5 { 
 padding-bottom: 62.50%; /* 8:5 */; 
 background: orange; 
}
div.aspectRatio_4-3 > div, div.aspectRatio_16-9 > div, div.aspectRatio_3-2 > div, div.aspectRatio_8-5 > div {
 position: absolute;
 top: 0;
 bottom: 0;
 left: 0;
 right: 0;
 color: white;
 font-size: 2.4em;
 text-align: center;
}
</style>
</head>
<body>
<div id="mainContainer">
 <div class="aspectRatio_4-3"><div>This is a div container with Aspect ratio 4:3. Resize your browser to see the effect.</div></div><br>
 <div class="aspectRatio_16-9"><div>This is a div container with Aspect ratio 16:9. Resize your browser to see the effect.</div></div><br>
 <div class="aspectRatio_3-2"><div>This is a div container with Aspect ratio 3:2. Resize your browser to see the effect.</div></div><br>
 <div class="aspectRatio_8-5"><div>This is a div container with Aspect ratio 8:5. Resize your browser to see the effect.</div></div><br>
</div>
</body>
</html>

Sample Output:


How to maintain aspect ratio in flexible or responsive layouts using CSS


Demo:



0 comments:

Post a Comment

Subscribe via Email