How To Prevent Image Stretching With Flexbox - Techstacker
Có thể bạn quan tâm
Learn how to prevent CSS’s Flexbox from stretching your image horizontally.
Flexbox has an odd default behavior where images get stretched horizontally to the full width of its parent container. So if you have a parent element (flex container) with flex-direction: column and a child element (flex item) which is an image, then the image’s natural height is maintained while the width is stretched as wide as the parent container.
This behavior is inconsistent, depending on your browser’s default CSS stylesheet (User Agent Stylesheet).
Fortunately, the solution is simple. You just need to replace your image/flex item’s align-self property’s default stretch value with another value.
Instead of stretch you can use center, which will remove the image stretching, and vertically align your image in the middle of its parent container.
img { align-self: center; }Example
Check out the following CSS example where we have 1 parent (flex container) and 2 children image elements (flex items) inside.
- The first image element has the browser default align-self: stretch which ruins the aspect ratio.
- On the second image element, I added a utility class called .self-center, with the align-self: center declaration which removes the stretching:
https://codepen.io/StrengthandFreedom/pen/qBBoMOX
Glorious, problem solved!
Note: you can also use top, to vertically align your image to the top of its parent container.
img { align-self: top; }Both methods will remove the stretch value from your image, but whether you should use top or center depends on what you want to do with your images.
Good to know
Flex items have a default align-self value of stretch. So whether your flex-item (child element) is an image or another HTML element, it gets stretched horizontally by default.
Từ khóa » Html Img Stretching
-
How To Resize An Image In HTML?
-
Html - How Do You Stretch An Image To Fill A
While Keeping The ...HTML Stretch Background Image
CSS Object-fit Property - W3Schools
How To Stretch And Scale An Image In The Background With CSS
How To Stretch A Background Image To Fit A Web Page - ThoughtCo
Stretch Image Html Code Example
Image Is Stretched Css Code Example
Stretch Background Image
How To Prevent Image From Stretching Css?
How To Stretch A Background Picture To Fill The Entire Website (or A ...
Object-fit | CSS-Tricks
Fit Image To Div Without Stretching | CSS Background-size Property
Display: Flex → Why Is The Logo Image Stretching Vertically - SitePoint
Copyright © 2022 | Thiết Kế Truyền Hình Cáp Sông Thu