Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to center an image with CSS?
To center an image on a web page, we have used the display, margin-left, and margin-right properties. Let us first see the display property.
The Display Property
To set an element as a block element, set the display property to block. In this case, our element is an image −
display: block;
The Margin-left Property
To set the left margin of an element, use the margin-left property in CSS. We have set the left margin for the image as auto that allows the web browser to calculate the left margin −
margin-left: auto;
The Margin-right Property
To set the right margin of an element, use the margin-right property in CSS. We have set the right margin for the image as auto that allows the web browser to calculate the left margin −
margin-right: auto;
Center an Image
Apply all the above properties on the image to center align an image −
img {
display: block;
margin-left: auto;
margin-right: auto;
width: 50%;
}
Example
The following is the code to center an image with CSS −
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
img {
display: block;
margin-left: auto;
margin-right: auto;
width: 50%;
}
</style>
</head>
<body>
<h1 style="text-align: center;">Example of centering an image</h1>
<img src="https://www.tutorialspoint.com/compiler_design/images/compiler-design-mini-logo.jpg">
</body>
</html>
Advertisements