Home >Web Front-end >CSS Tutorial >How to write the code to center the image in css
The following code can be used in CSS to center the image horizontally: Set the container element text-align: center;. Set the image as an inline block-level element display: inline-block;. Center the image vertically vertical-align: middle;. Center the image vertically: Set the container element to flexbox display: flex;. Center child elements vertically align-items: center;. Center child elements horizontally justify-content: center;. Limit image size max-width: 100%;, max-height:
Code for centering image display in CSS
Question: How to use CSS code to center the image horizontally and vertically in the element?
Answer:
Horizontal Centering
<code class="css">.image-container { text-align: center; } .image { display: inline-block; vertical-align: middle; }</code>
Vertical Centering
<code class="css">.image-container { display: flex; align-items: center; justify-content: center; } .image { max-width: 100%; max-height: 100%; }</code>
Details:
Horizontal center
Will
image- The container element is set to be horizontally centered.
Makes the
image element an inline block-level element, allowing it to be aligned with the text.
Center the
image element vertically, aligned with the surrounding text.
Vertically centered
image-container
element to flexbox , allowing flexible layout of its child elements.
image-container
element.
image-container
element horizontally.
max-height: 100%;
limit the size of the image
element so that it image-container
The size of the element while maintaining the aspect ratio.
The above is the detailed content of How to write the code to center the image in css. For more information, please follow other related articles on the PHP Chinese website!