programing

Flexbox가 가로 세로 비율을 유지하는 대신 이미지를 확장하는 이유는 무엇입니까?

stoneblock 2023. 8. 17. 20:33

Flexbox가 가로 세로 비율을 유지하는 대신 이미지를 확장하는 이유는 무엇입니까?

Flexbox에는 이미지를 자연 높이까지 확장하는 이러한 동작이 있습니다.즉, 하위 이미지가 있는 Flexbox 컨테이너를 사용하여 해당 이미지의 너비를 조정하면 높이가 전혀 크기 조정되지 않고 이미지가 늘어납니다.

div {
  display: flex; 
  flex-wrap: wrap;
}

img {
  width: 50%
}
<div>
    <img src="https://i.imgur.com/KAthy7g.jpg" >
    <h1>Heading</h1>
    <p>Paragraph</p>
</div>

원인이 무엇입니까?

기지개를 켜는 이유는align-self기본값은 입니다.stretch.세트align-self로.center.

align-self: center;

여기에서 설명서 참조: 자체 맞춤

주요 속성은align-self: center:

.container {
  display: flex;
  flex-direction: column;
}

img {
  max-width: 100%;
}

img.align-self {
  align-self: center;
}
<div class="container">
    <p>Without align-self:</p>
    <img src="http://i.imgur.com/NFBYJ3hs.jpg" />
    <p>With align-self:</p>
    <img class="align-self" src="http://i.imgur.com/NFBYJ3hs.jpg" />
</div>

추가 중margin이미지 정렬하기

우리가 원했기 때문에.image되려고left-aligned다음을 추가했습니다.

img {
  margin-right: auto;
}

마찬가지로image되려고right-aligned추가할 수 있습니다.margin-right: auto;이 스니펫은 두 가지 정렬 유형에 대한 데모를 보여줍니다.

행운을 빕니다...

div {
  display:flex; 
  flex-direction:column;
  border: 2px black solid;
}

h1 {
  text-align: center;
}
hr {
  border: 1px black solid;
  width: 100%
}
img.one {
  margin-right: auto;
}

img.two {
  margin-left: auto;
}
<div>
  <h1>Flex Box</h1>
  
  <hr />
  
  <img src="https://via.placeholder.com/80x80" class="one" 
  />
  
  
  <img src="https://via.placeholder.com/80x80" class="two" 
  />
  
  <hr />
</div>

align-self 기본값이 stretch이기 때문에 확장됩니다. 이 경우에는 1. set img align-self : center OR 2. set parent align-items : center 두 가지 솔루션이 있습니다.

img {
정렬-자체: 가운데}

OR

.부모님 {선형-곡선: 중심}

내비게이션 바를 만들 때도 비슷한 문제가 있었지만, 위의 내용 중 어느 것도 저에게 맞지 않았습니다.

내 솔루션은 다음을 추가하는 것이었습니다.height: 100%이미지를 위해.

항목을 수평으로 정렬하는 경우 추가width: 100%대신.

편집: 지금은 Chrome에서 기본적으로 이 값을 추가하는 것 같지만 호환성을 위해 이 값을 추가해야 합니다.

아래의 CSS 설정 중 하나를 사용합니다.contain또는cover가장 인기가 많음

.my-img {
  object-fit: contain;
}

또는

.my-img {
  object-fit: cover;
}

Foundation 메뉴에서도 동일한 문제가 발생했습니다.align-self: center;나한텐 안 통했어요

제 해결책은 이미지를 포장하는 것이었습니다.<div style="display: inline-table;">...</div>

저도 비슷한 문제가 있었습니다. 제 해결책은 다음과 같습니다.flex-shrink: 0;이미지에 맞게

언급URL : https://stackoverflow.com/questions/37609642/why-does-flexbox-stretch-my-image-rather-than-retaining-aspect-ratio