In CSS, you can center an image by: Using text-align properties: Set the image as a block element and set automatic left and right margins. Use flexbox layout: place the image into a flexbox container and set the horizontal and vertical centering properties. Use a grid layout: Place the image into a grid container and set both the horizontal and vertical center properties. Use absolute positioning: Remove the image from normal flow, center it horizontally and center it vertically with a transform.
How to center an image in CSS
In CSS, there are many ways to center an image:
Use text alignment attributes
<code class="css">img { display: block; margin: 0 auto; }</code>
display: block
Make the image a block element. margin: 0 auto
Automatically sets the left and right margins of the image so that it is centered horizontally within the parent element. Use flexbox layout
<code class="css">.container { display: flex; justify-content: center; align-items: center; } img { width: 100px; height: 100px; }</code>
.container
). justify-content: center
Center the child element (image) horizontally. align-items: center
Center the child elements vertically. Use grid layout
<code class="css">.container { display: grid; place-items: center; } img { width: 100px; height: 100px; }</code>
.container
). place-items: center
Centers child elements (images) both horizontally and vertically. Use absolute positioning
<code class="css">img { position: absolute; left: 50%; transform: translate(-50%, -50%); }</code>
left: 50%
Centers the image horizontally, but it will be centered relative to the left border of its parent element. transform: translate(-50%, -50%)
Moves the image 50% of its own width and height left and upward, centering it within the parent element. The above is the detailed content of How to set img center in css. For more information, please follow other related articles on the PHP Chinese website!