page 2
Method 1
<!DOCTYPE html> <html> <head> <style> .center { display: block; border: none; margin-left: auto; margin-right: auto; /* or simply use margin: 0 auto; */ } </style> </head> <body> <img class="center" src='https://www.encodedna.com/images/theme/css.png'> </body> </html>
The margin property creates space around an element. To center the image, from left and right or horizontally, I have set the margin-left and margin-right as auto. Or, you can simply use margin: 0 auto;. Both are same.
👉 You may also like this... How to rotate an Image using pure CSS
What does “auto” do in margin: 0 auto (or margin-left and margin-right)
The value auto automatically sets the left and right margin of an element at the center of a container. However, I am not using an element as a container. The image is display at the center of the page (the <body>).
Method 2
Unlike the previous (or the above) example, here I am going place the image exactly at the center of the screen. That is, centering horizontally and vertically.
<!DOCTYPE html> <html> <head> <style> .center { display: block; border: none; position: fixed; /* or absolute */ top: 50%; left: 50%; transform: translate(-50%, -50%); } </style> </head> <body> <img class="center" src='https://www.encodedna.com/images/theme/css.png'> </body> </html>
Not just image element, in-fact the above style (or method) can be used to center any element. See this example.