• Что бы вступить в ряды "Принятый кодер" Вам нужно:
    Написать 10 полезных сообщений или тем и Получить 10 симпатий.
    Для того кто не хочет терять время,может пожертвовать средства для поддержки сервеса, и вступить в ряды VIP на месяц, дополнительная информация в лс.

  • Пользаватели которые будут спамить, уходят в бан без предупреждения. Спам сообщения определяется администрацией и модератором.

  • Гость, Что бы Вы хотели увидеть на нашем Форуме? Изложить свои идеи и пожелания по улучшению форума Вы можете поделиться с нами здесь. ----> Перейдите сюда
  • Все пользователи не прошедшие проверку электронной почты будут заблокированы. Все вопросы с разблокировкой обращайтесь по адресу электронной почте : info@guardianelinks.com . Не пришло сообщение о проверке или о сбросе также сообщите нам.

Maximize Element Size While Maintaining Aspect Ratio with CSS

Sascha Оффлайн

Sascha

Заместитель Администратора
Команда форума
Администратор
Регистрация
9 Май 2015
Сообщения
1,605
Баллы
155

Introduction


When building video players, image viewers, or modal windows, you often need to maintain a specific aspect ratio while maximizing the available space.

This article demonstrates how to combine CSS aspect-ratio and object-fit properties to create a layout that automatically scales to fit its container while preserving a fixed aspect ratio.

Live Demo


See it in action here:

Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.



Common Challenges


Traditional approaches to maintaining aspect ratios have several drawbacks:

  • Padding-top hack: Using padding-top: 56.25% (for 16:9) is cryptic and hard to maintain
  • JavaScript calculations: Requires recalculation on window resize, impacting performance
  • Limited to images: Works for img tags but difficult to apply to arbitrary elements
The Solution


By combining CSS aspect-ratio and object-fit: contain, you can achieve this with clean, declarative code.

HTML Structure


Use three nested containers:


<div class="container">
<div class="inner">
<div class="aspect-ratio-lock">
<!-- Your contents -->
</div>
</div>
</div>



CSS Implementation


.container {
position: relative;
width: 100%;
height: 100%;
}

.inner {
position: absolute;
inset: 0;
max-width: 100%;
max-height: 100%;
aspect-ratio: 16 / 9;
object-fit: contain;
}

.aspect-ratio-lock {
width: 100%;
height: 100%;
/* Your content styles here */
}



How It Works

1. aspect-ratio: 16 / 9


Locks the element to a 16:9 ratio. You can use any ratio you need (e.g., 4 / 3, 1 / 1).

2. position: absolute + inset: 0


Positions .inner absolutely within .container, stretching it to fill the parent.

3. object-fit: contain


This is the key property. While typically used with img or video elements, when combined with aspect-ratio, it automatically scales any element to fit within its parent while maintaining the specified ratio.

4. max-width / max-height


Constrains the element to never exceed the parent's bounds.

Responsive Behavior


The beauty of this approach is that it automatically adapts to the parent's size without any JavaScript:

  • Tall container → Scales to width (leaves space top/bottom)
  • Wide container → Scales to height (leaves space left/right)

Everything is handled purely with CSS.

Practical Examples

Video Player Layout


.inner {
aspect-ratio: 16 / 9; /* Common video ratio */
}



Square Card


.inner {
aspect-ratio: 1 / 1;
}



Mobile Screen Preview


.inner {
aspect-ratio: 9 / 16; /* Portrait orientation */
}



Browser Support

  • aspect-ratio: Chrome 88+, Firefox 89+, Safari 15+
  • object-fit: Chrome 32+, Firefox 36+, Safari 10+

All modern browsers support this approach. For older browsers, you can provide a fallback using the padding-top hack.

Summary


Combining CSS aspect-ratio and object-fit: contain gives you:

✅ Simple, readable code
✅ No JavaScript required
✅ Support for any aspect ratio
✅ Automatic responsive behavior
✅ Works with any element (not just images)



Источник:

Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

 
Вверх Снизу