Responsive Div with Maintained Aspect Ratio Using CSS
When attempting to maintain an aspect ratio while resizing a div, you can leverage the power of CSS without relying on JavaScript.
CSS allows you to link the height and width of an element using percentages. Here's how to achieve it:
.wrapper { width: 50%; display: inline-block; position: relative; } .wrapper:after { padding-top: 56.25%; display: block; content: ''; } .main { position: absolute; top: 0; bottom: 0; right: 0; left: 0; background-color: deepskyblue; color: white; }
In this example, the wrapper div sets the desired width (50%). The wrapper:after pseudo-element uses a padding-top percentage relative to the wrapper's width. The value 56.25% corresponds to a 16:9 aspect ratio.
The main div fills the entire wrapper div, maintaining the aspect ratio specified by the padding-top percentage on the wrapper:after pseudo-element.
By utilizing CSS, you can easily maintain an aspect ratio for your div while resizing it responsively, without introducing JavaScript.
The above is the detailed content of How to Maintain Aspect Ratio of a Div Responsively Using Only CSS?. For more information, please follow other related articles on the PHP Chinese website!