- Сохраняем пропорции высоты и ширины элемента при изменении ширины контента на чистом CSS
- Решение проблемы
- HTML
- CSS
- Контент
- Другие пропорции
- IE7 и ниже
- Рабочий пример на CodePen:
- Вариант №2 — Сохраняем пропорции высоты и ширины элемента при изменении ширины контента на чистом CSS без псевдоэлементов
- HTML
- CSS
- Другие пропорции
- Рабочий пример на CodePen:
- doctor Brain
- Изображение фиксированного размера
- Изображение нефиксированного размера
- Заключение
- Полезно прочитать
- Новые публикации
- JavaScript: сохраняем страницу в pdf
- HTML: Полезные примеры
- CSS: Ускоряем загрузку страницы
- JavaScript: 5 странностей
- JavaScript: конструктор сортировщиков
- Категории
- О нас
- CSS force image resize and keep aspect ratio
- 26 Answers 26
- Best Practice (2018):
- Fancier Solution:
Сохраняем пропорции высоты и ширины элемента при изменении ширины контента на чистом CSS
Как пропорционально уменьшать ширину и высоту различных элементов при изменении ширины родительского контейнера?
Для изображений это делается очень просто, задаем свойству height значение auto , при этом максимальную ширину изображения ограничиваем шириной родительского контейнера max-width: 100%;
Проблема в том, что мы не можем задать height: auto; для блочных элементов, например для DIV. В данном случае 100% — это будет высота родителя.
Решение проблемы
HTML
Нам нужны два блочных элемента для достижения желаемого поведения. Нет изображений, нет Javascript.
CSS
Итак, что это? Мы определяем псевдоэлемент для нашего ящика и задаем ему margin-top 100% . Поскольку это 100% значение относится к ширине элемента … вы получаете его ( height: 0; padding-bottom: 100%; также будет работать, но тогда вы должны отрегулировать значение padding-bottom каждый раз, когда вы меняете ширину).
Таким образом, наш блок уже выше ширины. Если вы хотите отображать только несколько цветных блоков, тогда уже все готово. Но поскольку пользовательский интерфейс намного сложнее, и если вы также предоставляете некоторый контент, мы добавляем контент в наш блок .box .
Контент
И вот трюк: мы просто позиционируем блок контента как абсолютный со всеми четырьмя ориентациями, установленными в 0. Это просто покрывает родительский элемент полностью, независимо от того, какой размер он имеет.
Вот и все. Блестяще, не так ли? Даже padding не сломает его, и нет необходимости в box-sizing: border-box здесь.
Другие пропорции
Если вы хотите создать другие коэффициенты, просто измените значение padding-top псевдоэлемента:
/* Other ratios */ .ratio2_1:before < padding-top: 50%; >.ratio1_2:before < padding-top: 200%; >.ratio4_3:before < padding-top: 75%; >.ratio16_9:before
IE7 и ниже
Поскольку IE такой IE, и особенно IE7 — это все, но только не браузер, вы должны сами создать элемент вместо псевдоэлемента в своей разметке, если хотите поддержать IE. Или бросьте на него Javascript, пока он, надеюсь, не сломается. Навсегда.
Мой вольный перевод статьи http://www.mademyday.de/css-height-equals-width-with-pure-css.html.
Рабочий пример на CodePen:
Вариант №2 — Сохраняем пропорции высоты и ширины элемента при изменении ширины контента на чистом CSS без псевдоэлементов
Есть второй вариант без псевдоэлементов, но при его использовании блок всегда имеет ширину 100%, поэтому если нужно несколько таких блоков в ряд, то они должны быть помещены в какой-то родитель, у которого уже будет задана нужная ширина относительно остальных элементов на странице.
HTML
CSS
.box < background-color: red; width: 100%; padding-top: 100%; /* 1:1 Aspect Ratio */ position: relative; >/* If you want text inside of the container */ .content
Другие пропорции
.ratio16_9 < padding-top: 56.25%; /* 16:9 Aspect Ratio */ >.ratio4_3 < padding-top: 75%; /* 4:3 Aspect Ratio */ >.ratio3_2 < padding-top: 66.66%; /* 3:2 Aspect Ratio */ >/* Other ratios */ .ratio8_5 < padding-top: 62.5%; /* 8:5 Aspect Ratio */ >
Рабочий пример на CodePen:
Самый простой пример фиксированного плавающего сайдбара на HTML+CSS+JS. В чем его особенность — при прокрутке…
Еще один фиксированный блок Меню при прокрутке страницы. Было бы замечательно, если бы IE поддерживало…
Простая инструкция, как перенести сайт на CMS WordPress с одного хостинга на другой. На самом…
Суть задачи, чтобы видео, которое находится где-то на странице, включалось только при прокрутке страницы, когда…
doctor Brain
В этом очень небольшом обзоре мы изучим, как установить соотношение сторон (пропорции) для изображения, размещаемого на HTML-странице. Для чего это нужно? К примеру, полученные знания будут полезны, если возникает необходимость уместить картинки различных размеров и пропорций в квадратный блок (или любой другой блок с четко определенными размерами и соотношением сторон), не искажая изображения.
Следует понимать, что в данном случае мы будем манипулировать CSS-свойствами, ни одно изображении не пострадает и сохранит свое первозданное состояние.
Изображение фиксированного размера
Если на страницу нужно вывести картинку заранее определенных размеров, можно воспользоваться атрибутами width и height .
Так как мы не знаем размеры и пропорции исходного изображения, применим CSS-свойство object-fit . Таким образом, мы сможем быть уверены, что картинка не деформируется.
Результат можно увидеть на нижеприведенной иллюстрации. Заметьте: исходное изображение имеет большую ширину, но оно не подверглось искажениям, вместо этого оно “обрезано” по центру:
Свойство object-fit принимает значения fill , contain , cover , none , scale-down . Подробно информацию можно изучить на сайте MDN.
Изображение нефиксированного размера
Чтобы привести картинку, изменяющую свои размеры вместе с родительским блоком, к определенным пропорциям нужно воспользоваться оберткой. Оборачивающий элемент заставит изображение сохранять определенные пропорции, так как само изображение заполнит всю его площадь.
/* Position child elements relative to this element */ .aspect-ratio-box < position: relative; >/* Create a pseudo element that uses padding-bottom to take up space */ .aspect-ratio-box::after < display: block; content: ''; /* 16:9 aspect ratio */ padding-bottom: 56.25%; >/* Image is positioned absolutely relative to the parent element */ .aspect-ratio-box img < /* Image should match parent box size */ position: absolute; left: 0; top: 0; width: 100%; height: 100%; >
Приблизительно так будет выглядеть результат при соотношении сторон 16:9:
Свойство padding-bottom определяет высоту родительского контейнера, выраженную в процентах от его ширины. Например, при ширине блока 400px результирующая высота составит 56,25% от 400px, то есть около 225px.
Для того, чтобы определить нужное нам значение padding-bottom необходимо разделить высоту на ширину.
Например, при соотношении сторон 16:9, арифмитические манипуляции будут выглядеть так:
Выразим результ в процентах (умножим полученное число на 100):
Заключение
Мы научились выводить на HTML-изображение в различных пропорциях без деформации исходной картинки. Предложенные варианты работы с изображениями фиксированных и нефиксированных охватывают значительную часть стандартных ситуаций, возникающих при верстке.
Полезно прочитать
Новые публикации
JavaScript: сохраняем страницу в pdf
HTML: Полезные примеры
CSS: Ускоряем загрузку страницы
JavaScript: 5 странностей
JavaScript: конструктор сортировщиков
Категории
О нас
Frontend & Backend. Статьи, обзоры, заметки, код, уроки.
© 2021 dr.Brain .
мир глазами веб-разработчика
CSS force image resize and keep aspect ratio
But for big_image.jpg , I receive width=500 and height=600 . How do I set images to be re-sized, whilst keeping their aspect ratios.
26 Answers 26
This image is originally 400x400 pixels, but should get resized by the CSS:

This will make image shrink if it’s too big for specified area (as downside, it will not enlarge image).
Is there a version of this that will enlarge images to fit their container also? I’ve tried the max-width/max-height as numbers with width/height as auto, but as setec said above, it will not enlarge the image. I’ve tried using min-width/min-height also. I just can’t get the combination right. I simply want that whatever image I have to put into this container, it will display at it’s maximum size possible without changing aspect ratio regardless of whether that involves shrinking or growing the image to achieve that.
Note that the question was about an that itself includes a width and height and I think that means you need to use !important to circumvent the tag width/height info.
object-fit: cover; width: 100%; height: 250px;
You can adjust the width and height to fit your needs, and the object-fit property will do the cropping for you.
More information about the possible values for the object-fit property and a compatibility table are available here: https://developer.mozilla.org/en-US/docs/Web/CSS/object-fit
The solutions below will allow scaling up and scaling down of the image, depending on the parent box width.
All images have a parent container with a fixed width for demonstration purposes only. In production, this will be the width of the parent box.
Best Practice (2018):
This solution tells the browser to render the image with max available width and adjust the height as a percentage of that width.
This image is originally 400x400 pixels, but should get resized by the CSS:

Fancier Solution:
With the fancier solution, you’ll be able to crop the image regardless of its size and add a background color to compensate for the cropping.
.parent < width: 100px; >.container < display: block; width: 100%; height: auto; position: relative; overflow: hidden; padding: 34.37% 0 0 0; /* 34.37% = 100 / (w / h) = 100 / (640 / 220) */ >.container img
This image is originally 640x220, but should get resized by the CSS:
For the line specifying padding, you need to calculate the aspect ratio of the image, for example:
640px (w) = 100% 220px (h) = ? 640/220 = 2.909 100/2.909 = 34.37%
I don’t get it. I’ve loaded full HD images with both this and the accepted answer’s solution. Is it really being scaled becasue I can’t tell (tested on chrome and IE10+)
I love how standardization organizations were in a meeting once and all agreed: this should be the way people are going to achieve the desired result.
2018 solution is bad, when the parent has width/height ratio smaller than the image width/height ratio, the image end up stretched badly.
That won’t make too much sense. It’s a 15k lines of code web architecture. The specific code you posted will result in correct scaling for images that have lower aspect ratios than that of their parent container, but will not work if it is vice versa, resulting in stretching. I was specifically looking for a dynamic approach, as prior I do not know DIV size or image dimensions. In the end I solved this by preloading the image, calculating the aspect ratio, comparing it versus the aspect ratio of the area and then apply the proper CSS style.
Very similar to some answers here, but in my case I had images that sometimes were taller, sometimes larger.
This style worked like a charm to make sure that all images use all available space, keep the ratio and not cuts:
Is .img a class on the parent or the image? Could you make a jsfiddle with example for both portrait and landscape images?
Upvoted because it’s the first to mention object-fit: contain . In my experience, all that’s necessary is that plus either a height or width.
The background-size property is ie>=9 only, but if that is fine with you, you can use a div with background-image and set background-size: contain :
Now you can just set your div size to whatever you want and not only will the image keep its aspect ratio it will also be centralized both vertically and horizontally within the div. Just don’t forget to set the sizes on the css since divs don’t have the width/height attribute on the tag itself.
This approach is different than setecs answer, using this the image area will be constant and defined by you (leaving empty spaces either horizontally or vertically depending on the div size and image aspect ratio), while setecs answer will get you a box that exactly the size of the scaled image (without empty spaces).
Edit: According to the MDN background-size documentation you can simulate the background-size property in IE8 using a proprietary filter declaration:
Though Internet Explorer 8 doesn’t support the background-size property, it is possible to emulate some of its functionality using the non-standard -ms-filter function:
-ms-filter: "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='path_relative_to_the_HTML_file', sizingMethod='scale')";