Html img width relative

CSS: How can I set image size relative to parent height?

I am trying to figure out how to re-size an image so that it keeps it ratio of width to height, but gets re-sized until the height of the image matches the height of the containing div. I have these images that are pretty large and long (screenshots), and I want to put them into a 200px width, 180px height div for display and without re-sizing the images manually. To make this look good, the sides of the image need to overflow and be hidden with the containing div. This is what I have so far: http://jsfiddle.net/f9krj/2/ HTML

a.image_container < background-color: #999; width: 200px; height: 180px; display: inline-block; overflow: hidden; >a.image_container img

As you can see, there is grey color showing on the images parent container which should not be shown at all. In order for that container to be filled completely, the width needs to be overflowed equally on both sides. Is this possible? Is it also possible to account for an image that is also too tall?

7 Answers 7

Original Answer:

If you are ready to opt for CSS3, you can use css3 translate property. Resize based on whatever is bigger. If your height is bigger and width is smaller than container, width will be stretch to 100% and height will be trimmed from both side. Same goes for larger width as well.

Your need, HTML:

 

Explanation

DIV is set to the relative position. This means all the child elements will get the starting coordinates (origins) from where this DIV starts.

The image is set as a BLOCK element, min-width/height both set to 100% means to resize the image no matter of its size to be the minimum of 100% of it’s parent. min is the key. If by min-height, the image height exceeded the parent’s height, no problem. It will look for if min-width and try to set the minimum height to be 100% of parents. Both goes vice-versa. This ensures there are no gaps around the div but image is always bit bigger and gets trimmed by overflow:hidden;

Читайте также:  Matplotlib python масштаб осей

Now image , this is set to an absolute position with left:50% and top:50% . Means push the image 50% from the top and left making sure the origin is taken from DIV. Left/Top units are measured from the parent.

Magic moment:

Now, this translate function of CSS3 transform property moves/repositions an element in question. This property deals with the applied element hence the values (x, y) OR (-50%, -50%) means to move the image negative left by 50% of image size and move to the negative top by 50% of image size.

Eg. if Image size was 200px × 150px, transform:translate(-50%, -50%) will calculated to translate(-100px, -75px). % unit helps when we have various size of image.

This is just a tricky way to figure out centroid of the image and the parent DIV and match them.

Apologies for taking too long to explain!

Источник

doctor Brain

В этом очень небольшом обзоре мы изучим, как установить соотношение сторон (пропорции) для изображения, размещаемого на HTML-странице. Для чего это нужно? К примеру, полученные знания будут полезны, если возникает необходимость уместить картинки различных размеров и пропорций в квадратный блок (или любой другой блок с четко определенными размерами и соотношением сторон), не искажая изображения.

Следует понимать, что в данном случае мы будем манипулировать CSS-свойствами, ни одно изображении не пострадает и сохранит свое первозданное состояние.

Изображение фиксированного размера

Если на страницу нужно вывести картинку заранее определенных размеров, можно воспользоваться атрибутами width и height .

Так как мы не знаем размеры и пропорции исходного изображения, применим CSS-свойство object-fit . Таким образом, мы сможем быть уверены, что картинка не деформируется.

Читайте также:  Css удалить неиспользуемые стили css

Результат можно увидеть на нижеприведенной иллюстрации. Заметьте: исходное изображение имеет большую ширину, но оно не подверглось искажениям, вместо этого оно “обрезано” по центру:

object-fit: cover

Свойство 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:

16:9

Свойство padding-bottom определяет высоту родительского контейнера, выраженную в процентах от его ширины. Например, при ширине блока 400px результирующая высота составит 56,25% от 400px, то есть около 225px.

Для того, чтобы определить нужное нам значение padding-bottom необходимо разделить высоту на ширину.

Например, при соотношении сторон 16:9, арифмитические манипуляции будут выглядеть так:

Выразим результ в процентах (умножим полученное число на 100):

Заключение

Мы научились выводить на HTML-изображение в различных пропорциях без деформации исходной картинки. Предложенные варианты работы с изображениями фиксированных и нефиксированных охватывают значительную часть стандартных ситуаций, возникающих при верстке.

Полезно прочитать

Новые публикации

Photo by CHUTTERSNAP on Unsplash

JavaScript: сохраняем страницу в pdf

HTML: Полезные примеры

CSS: Ускоряем загрузку страницы

JavaScript: 5 странностей

JavaScript: конструктор сортировщиков

Категории

О нас

Frontend & Backend. Статьи, обзоры, заметки, код, уроки.

© 2021 dr.Brain .
мир глазами веб-разработчика

Источник

img width relative to containing div

What is the most efficient way to calculate the width of an image relative to it’s containing div in css? I have the following snippet which sets #image1.width to a percentage that is relative to the width of its parent. I’m using a percentage because I need the image to scale proportionately to the parent when the screen is resized.

 

It is currently working as intended, except that I have to manually calculate the width percentage for every single image. i.e.

#image1 dimensions == 206x115 #under dimensions == 700x300 new #image1.width % == #image1.width / #under.width == 206/700 == ~29.43% 

What I want to know is if there id a calc() method or similar I can implement to ease/streamline this process? I was going to use width: calc(100% / 700) however this obviously will not work when the screen size changes.

Читайте также:  Javascript get all user info

Goals

To re-iterate, it is imperative that the #under image scales with the screen size and the #image remains proportionate. I want the natural image ratios preserved with one another (i.e. an image that is one quarter the size of the other will remain as such at all browser widths). Note: The html can be reconfigured in any way to achieve this. Target browsers: Chrome, Firefox, Edge.

Post Bounty Review

Comment on @Obsidian Age’s answer (end of first bounty 31.03.17): Unfortunately @Obsidian Age’s answer is not correct — it is close but not quite and I just wanted to clarify this here. Below is a snippet from his answer. Note that I think it is a good answer, just clarifying why it has not been accepted:

Setting —width: 90vw what happens if body or div have a max-width set? This is also very hard to calculate for all devices when factoring in viewport-scaling . #image1 < width:calc(var(--width) / 3); >This equates to calc(90vw / 3) which is 30vw which would equate to 30% of the images width. But how do we work out the number to divide by? Well it’s back to where we started. width:calc(var(—width) * calc(206/700*100)); And this is why I have not accepted this answer.

Источник

Оцените статью