I am trying to center a image horizontally using css.
I am displaying my image on the screen with the following HTML code:
<div id="loading" class="loading-invisible"> <img class="loading" src="logo.png"> </div>
I am croping my image as I only want to display some of the image and I am using the following css:
img.loading { position:absolute; clip:rect(0px,681px,75px,180px); }
however I can't work out how to center the image once it has been croped.
Anyone able to help ?
Step 1: Wrap the image in a div element. Step 2: Set the display property to "flex," which tells the browser that the div is the parent container and the image is a flex item. Step 3: Set the justify-content property to "center." Step 4: Set the width of the image to a fixed length value.
To center an image with CSS Grid, wrap the image in a container div element and give it a display of grid . Then set the place-items property to center. P.S.: place-items with a value of center centers anything horizontally and vertically.
We can use flex-box to center an image horizontally and vertically. To do so we must use both the justify-content and align-items property on the parent container of the image. All we then have to do is give them both the value of center and bobs your uncle, that image is centered both horizontally and vertically.
If you want to center something horizontally in CSS you can do it just by, using the text-align: center; (when working with inline elements) or margin: 0 auto; (when working with block element).
Try this for your CSS:
.center img { display:block; margin-left:auto; margin-right:auto; }
and then add to your image to center it:
class="center"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With