Setting default max-width and height for img tag
Problem
Pull request #426 sets height to auto in combination with a default value of max-width to 100% to the `img` tag. This gives unexpected results. See Codepen. Loading a 100x200px image fills up the whole space although I am setting width and height specifically. @adevade mentioned code from Bootsrap, but this is meant for a fluid image with class name `image-fluid`. I took a look at the source code of BeardCSS. BeardCSS is setting only a max-width of 100%, if width or height attributes are set they will be respected by resetting max-width to none on the `img` tag. I think we should take the BeardCSS approach. Example of same code as above with the BeardCSS approach gives the expected result.
Unverified for your environment
Select your OS to check compatibility.
1 Fix
Implement BeardCSS Approach for img Tag Resizing
The current implementation sets the max-width of the img tag to 100% and height to auto, which causes images to stretch and fill the available space regardless of their intrinsic dimensions. This behavior conflicts with the expectation that images should respect their specified width and height attributes. By following the BeardCSS approach, we can ensure that the max-width is only applied when no width or height attributes are set, allowing for more predictable image rendering.
Awaiting Verification
Be the first to verify this fix
- 1
Remove height:auto from img styles
Remove the automatic height setting from the img tag styles to prevent distortion of images when specific width and height attributes are provided.
cssimg { height: auto; } - 2
Set max-width to none when width/height are specified
Modify the CSS to set max-width to none when the img tag has explicit width or height attributes. This ensures that the intrinsic dimensions of the image are respected.
cssimg[width][height] { max-width: none; } - 3
Test with various image sizes
Load images of different sizes (e.g., 100x200px, 200x100px, etc.) to verify that the images render correctly according to their specified dimensions without stretching.
javascriptconst images = document.querySelectorAll('img'); images.forEach(img => console.log(img.width, img.height)); - 4
Update documentation
Update any relevant documentation to reflect the new behavior of the img tag, ensuring developers understand how to use the image-fluid class correctly.
- 5
Review and merge changes
After testing, review the changes with the team and merge the pull request to implement the fix in the main branch.
Validation
To confirm the fix worked, load the application and check that images with specified width and height attributes render correctly without distortion. Use browser developer tools to inspect the computed styles and ensure max-width is set to none for images with defined dimensions.
Sign in to verify this fix
Environment
Submitted by
Alex Chen
2450 rep