developer tip

높이 변경시 이미지 종횡비 유지

optionbox 2020. 8. 7. 08:21
반응형

높이 변경시 이미지 종횡비 유지


CSS 플렉스 박스 모델을 사용하여 이미지가 종횡비를 유지하도록 강제 할 수 있습니까?

JS Fiddle : http://jsfiddle.net/xLc2Le0k/2/

컨테이너의 너비를 채우기 위해 이미지가 늘어나거나 줄어 듭니다. 괜찮습니다.하지만 이미지 비율을 유지하기 위해 높이늘리거나 줄일 수도 있습니까?

HTML

<div class="slider">
    <img src="http://www.placebacon.net/400/300" alt="Bacn">
    <img src="http://www.placebacon.net/400/300" alt="Bacn">
    <img src="http://www.placebacon.net/400/300" alt="Bacn">
    <img src="http://www.placebacon.net/400/300" alt="Bacn">
</div>

CSS

.slider {
    display: flex;
}
.slider img {
    margin: 0 5px;
}

img 태그의 경우 한쪽을 정의하면 다른 쪽의 크기가 조정되어 종횡비를 유지하고 기본적으로 이미지가 원래 크기로 확장됩니다.

이 사실을 사용하여 각 img 태그를 div 태그로 래핑하고 너비를 부모 div의 100 %로 설정하면 높이가 원하는 가로 세로 비율에 따라 달라집니다.

http://jsfiddle.net/0o5tpbxg/

* {
    margin: 0;
    padding: 0;
}
.slider {
    display: flex;
}
.slider .slide img {
    width: 100%;
}

플렉스 부모 내부의 어느 축에서나 이미지가 늘어나지 않도록 몇 가지 해결책을 찾았습니다.

예를 들어 이미지에 개체 맞춤을 사용해 볼 수 있습니다.

object-fit: contain;

http://jsfiddle.net/ykw3sfjd/

또는 경우에 따라 더 잘 작동 할 수있는 플렉스 특정 규칙을 추가 할 수 있습니다.

align-self: center;
flex: 0 0 auto;

포함하는 div를 추가 할 필요가 없습니다.

css "align-items"속성의 기본값은 "stretch"로 이미지가 원래 높이까지 늘어납니다. css "align-items"속성을 "flex-start"로 설정하면 문제가 해결됩니다.

.slider {
    display: flex;
    align-items: flex-start;  /* ADD THIS! */
}

본질적인 크기를 가진 대부분의 이미지 , 즉 jpeg이미지 처럼 자연스러운 크기 입니다. 지정된 크기가 너비와 높이 중 하나를 정의하는 경우 고유 비율을 사용하여 누락 된 값이 결정됩니다 ...- MDN 참조 .

그러나 내가 아는 한 현재 Flexible Box Layout Module Level 1을 사용하여 직접 플렉스 항목으로 설정되는 이미지가 예상대로 작동하지 않습니다 .

다음 토론을 참조하고 버그 보고서가 관련 될 수 있습니다.

  • Flexbugs # 14 -Chrome / Flexbox Intrinsic Sizing이 올바르게 구현되지 않았습니다.
  • Firefox 버그 972595 -Flex 컨테이너는 flex 항목의 고유 너비를 계산하기 위해 "width"대신 "flex-basis"를 사용해야합니다.
  • Chromium 문제 249112 -Flexbox에서 고유 종횡비를 허용하여 기본 크기 계산을 알립니다.

해결 방법으로 각각 <img><div>또는로 래핑 할 수 <span>있습니다.

jsFiddle

.slider {
  display: flex;
}

.slider>div {
  min-width: 0; /* why? see below. */
}

.slider>div>img {
  max-width: 100%;
  height: auto;
}
<div class="slider">
  <div><img src="https://picsum.photos/400/300?image=0" /></div>
  <div><img src="https://picsum.photos/400/300?image=1" /></div>
  <div><img src="https://picsum.photos/400/300?image=2" /></div>
  <div><img src="https://picsum.photos/400/300?image=3" /></div>
</div>

4.5 플렉스 아이템의 묵시적 최소 크기

To provide a more reasonable default minimum size for flex items, this specification introduces a new auto value as the initial value of the min-width and min-height properties defined in CSS 2.1.


Alternatively, you can use CSS table layout instead, which you'll get similar results as flexbox, it will work on more browsers, even for IE8.

jsFiddle

.slider {
  display: table;
  width: 100%;
  table-layout: fixed;
  border-collapse: collapse;
}

.slider>div {
  display: table-cell;
  vertical-align: top;
}

.slider>div>img {
  max-width: 100%;
  height: auto;
}
<div class="slider">
  <div><img src="https://picsum.photos/400/300?image=0" /></div>
  <div><img src="https://picsum.photos/400/300?image=1" /></div>
  <div><img src="https://picsum.photos/400/300?image=2" /></div>
  <div><img src="https://picsum.photos/400/300?image=3" /></div>
</div>


I have been playing around flexbox lately and i came to solution for this through experimentation and the following reasoning. However, in reality I'm not sure if this is exactly what happens.

If real width is affected by flex system. So after width of elements hit max width of parent they extra width set in css is ignored. Then it's safe to set width to 100%.

Since height of img tag is derived from image itself then setting height to 0% could do something. (this is where i am unclear as to what...but it made sense to me that it should fix it)

DEMO

(remember saw it here first!)

.slider {
    display: flex;
}
.slider img {
    height: 0%;
    width: 100%;
    margin: 0 5px;
}

Works only in chrome yet


This behavior is expected. flex container will stretch all its children by default. Image have no exception. (ie, parent will have align-items: stretch property )

To keep the aspect ratio we've two solutions:

  1. Either replace default align-items: stretch property to align-items: flex-start or align-self: center etc, http://jsfiddle.net/e394Lqnt/3/

or

  1. Set align property exclusively to the child itself: like, align-self: center or align-self: flex-start etc. http://jsfiddle.net/e394Lqnt/2/

Actually I found out that the container of the image tag need to have a height in order to keep the ratio of the image. for example>

.container{display:flex; height:100%;} img{width:100%;height:auto;}

then in your html your container will wrap the tag image

<div class="container"><img src="image.jpg" alt="image" /></div>

this work for IE and other browsers


I just had the same issue. Use the flex align to center your elements. You need to use align-items: center instead of align-content: center. This will maintain the aspect ratio, while align-content will not keep the aspect ratio.

참고URL : https://stackoverflow.com/questions/30788131/maintain-image-aspect-ratio-when-changing-height

반응형