Home > Article > Web Front-end > How to center the image with css
In web design, pictures, as an important part of the page, often need to be set to be displayed in the center. This article will introduce how to center the image through CSS.
The first method: use the text-align attribute
The text-align attribute specifies the horizontal alignment of the text content within an element. It is generally used for block-level elements, but can also be used for in-line element. When the text-align attribute is set to center, the text content within the element will be aligned horizontally and center. When the text content is an image, the image will also be centered.
<!DOCTYPE html> <html> <head> <style> .center { text-align: center; } </style> </head> <body> <div class="center"> <img src="example.jpg" alt="example image"> </div> </body> </html>
As shown in the above code, by nesting the image in a div element with the text-align:center attribute, the image can be displayed in the center.
Second method: Use the margin attribute
The margin attribute is used to set the margins of the element and push the element outwards away from other elements or boundaries. When using the margin attribute and setting its left and right margins to auto, the element content will automatically be centered.
<!DOCTYPE html> <html> <head> <style> .center { margin: 0 auto; display: block; } </style> </head> <body> <img src="example.jpg" alt="example image" class="center"> </body> </html>
As shown in the above code, by adding the class attribute to the image, and then setting the marginLeft and marginRight of the class element to auto in the CSS style, and setting the display attribute to block, the image can be centered. show.
Third method: Use flex layout
Flex layout is a flex box model that allows better control of the items in the flex container. Flexbox controls the alignment of child elements in the container through the attributes align-items, justify-content and align-self. When both the align-items and justify-content properties of flex are set to center, the items in the container will automatically be aligned in the center.
<!DOCTYPE html> <html> <head> <style> .container { display: flex; align-items: center; justify-content: center; } </style> </head> <body> <div class="container"> <img src="example.jpg" alt="example image"> </div> </body> </html>
As shown in the above code, by adding the flex layout attribute to a parent container containing an image, the image can be automatically aligned in the center.
In summary, the above three methods can easily achieve centered display of images. You can choose the appropriate method according to the specific situation to achieve the best display effect.
The above is the detailed content of How to center the image with css. For more information, please follow other related articles on the PHP Chinese website!