How to maintain the aspect ratio of an element with CSS?

CSSWeb DevelopmentFront End Technology

To maintain the aspect ration of an element with CSS, the code is as follows −


 Live Demo

<!DOCTYPE html>
<meta name="viewport" content="width=device-width, initial-scale=1">
      font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
   .aspectContainer {
      background-color: rgb(191, 66, 216);
      position: relative;
      width: 100%;
      padding-top: 75%;
   .aspectText {
      position: absolute;
      text-align: center;
      top: 0;
      left: 0;
      bottom: 0;
      right: 0;
      Text-align: center;
      font-size: 20px;
      color: white;
<h1>Aspect ratio example</h1>
<div class="aspectContainer">
<div class="aspectText">4:3 Aspect ratio</div>
<h2>Resize the window to see 4:3 aspect ratio in action</h2>


The above code will produce the following output −

On resizing the window the element will shrink in the ratio 4:3 −

Updated on 08-May-2020 13:18:13