I have this div that has a width of 100% and a height of 90px. Inside the div I have a img that is 90px in height, but I let the width set itself. So how do I set the img withing the div, without knowing it's width?
-
`margin: 0 auto` – Justinas May 11 '21 at 06:30
-
try setting your child element's width to 'fit-content' or 'inherit' – NIV May 11 '21 at 06:32
-
What do you want to happen if, at height 90px, the image is too wide for the container? – A Haworth May 11 '21 at 07:02
2 Answers
There is some useful discussion on the centering of img elements at https://stackoverflow.com/questions/34247337/object-fit-not-affecting-images
Here's a snippet which centers an img based on the recent answer in that link from @MohammadImami
You can try altering the dimensions of the img (the last two in the url are width and height respectively) to see what happens. All is fine unless the img is so wide compared to its height of 90px that it wont fit, in which case this code shrinks the height to ensure the whole img is included in the container. It is centered vertically as well as horizontally. I don't know whether this is a situation you will encounter. It seems like the most sensible thing to do - so none of the img is cropped out. But I don't know your requirement in this extreme situation.
.container {
width: 100%;
height: 90px;
}
.container img {
height: inherit;
width: inherit;
object-fit: contain;
object-position: center;
}
<div class="container">
<img src="https://picsum.photos/id/1016/1024/768">
</div>

- 30,908
- 4
- 11
- 14
If you want to center the image inside the div, you can try
img {
margin: 0 auto;
}
It will let the top and bottom margin as 0px and right and left as auto (centered).
If you want the image to cover the entire width, use the background-image property
div {
background-image: url('image.jpg');
}
I don't know if this is what you wanted to do.

- 1
- 1