https://blog.hubspot.com/website/center-an-image-in-html#how-to-horizontally-center-an-image-in-css
Method 3: Using the Flex Property
I can also center an image horizontally using the flex property, which doesn’t require margin calculations.
how to center an image in css, flex
Here's how:
In my HTML file, I start by looking for the image I want to center.
From there, I set the width of the image to a fixed length value, i.e
.
I can then wrap the image in a div element. I also have the option of giving the div an ID or class. That way, the centering code only applies to this one specific instance and not to all divs.
Next, I open up my CSS file.
I can then find my div selector or write out my ID or class selector (#example or .example).
Inside the curly brackets, I set the display property to flex, which tells the browser that the div is the parent container and the image is a flex item.
Then, I set the justify-content property to center.
Here's the CSS with the result:
Try it yourself! The code module above is editable. Toggle between the HTML and CSS tabs, edit the code, and click rerun in the bottom right-hand corner.
Click on the HTML button to see the HTML code as well.
Pro tip: As previously mentioned and speaking from personal experience, I encourage you to give an ID selector to your div and use the selector in your CSS code. That way, all divs on your website aren’t affected.
https://www.youtube.com/watch?v=PFfAuNGarYk
-=-=-HTML
Centering an Image with the Flex Property
In this example, the CSS flex property is used to center the image below.
The image is wrapped in a div element. The display property is set to "flex" and justify-content property to "center." The width of the image is then set to a fixed length value.
-=-=-CSS
body {
margin: auto;
width: 640px;
padding: 50px;
font-family: 'Arial', sans-serif;
color: #33475b;
}
/* Centered Image Code */
div {
display: flex;
justify-content: center;
}
-=-=-