Skip to main content

Maintaining Aspect Ratio with CSS: Setting 100% Width or Height

Updated by Tim Rabbetts on
CSS Techniques for Maintaining Aspect Ratio

Creating responsive designs that maintain aspect ratios while achieving 100% width or height can be a challenge. However, with modern CSS, there are effective ways to keep elements such as images, videos, and containers properly scaled. Here, we explore several techniques that ensure visual integrity across different screen sizes and resolutions.

Using Padding for Aspect Ratio

One popular method involves using the top or bottom padding of a container relative to its width. This technique is especially useful for media elements like videos and images. The aspect ratio can be maintained by setting a percentage-based padding-top that reflects the height-to-width ratio of the content.

                
                    .aspect-ratio-box {
                        width: 100%;
                        padding-top: 56.25%; /* 16:9 Aspect Ratio */
                        position: relative;
                    }
                    
                    .content {
                        position: absolute;
                        top: 0;
                        left: 0;
                        right: 0;
                        bottom: 0;
                    }
                
            

CSS Aspect Ratio Property

Introduced in more recent versions of CSS, the aspect-ratio property allows developers to directly set an aspect ratio on any box, ensuring that it respects this ratio regardless of the width or height provided. When one dimension is set to 100%, the other adjusts accordingly.

                
                    .responsive-container {
                        width: 100%;
                        aspect-ratio: 16 / 9;
                    }
                
            

Using SVG for Maintaining Ratios

An SVG with a predefined viewBox and an aspect ratio can be used as a flexible spacer or container. The SVG will scale fluidly, and you can use it to wrap an image or a video element.

                
                    <svg width="100%" height="100%" viewBox="0 0 16 9" preserveAspectRatio="xMidYMid slice">
                        <image xlink:href="path_to_image.jpg" width="16" height="9"/>
                    </svg>
                
            

All these methods provide robust solutions for maintaining aspect ratios in responsive designs. Whether you’re working with media, canvases, or other responsive content, these CSS techniques should help in keeping your layouts consistent and visually appealing.