In this post we will learn how to center an image with the help of HTML and CSS. It is quite difficult to center the image while retaining the layout of the web page. In this post, we will learn about many such methods of HTML and CSS so that we will be able to center the image easily.


How To Center An Image with HTML and CSS ?


How To Center An Image ?

Different methods to center an image are as follows:


Method : 1

In this method we center the image using margin and display property. To center the image, we set the left and right margin to auto and convert it into a block element. With this, we set the value of width to 50%.


<!DOCTYPE html>
<html>
<head>
<title>How To Center An Image with HTML and CSS ?</title>
<style>
img {
display: block;
margin-left: auto;
margin-right: auto;
width: 50%;
}
</style>
</head>
<body>

<p>Example paragraph text. Example paragraph text. Example paragraph text. Example paragraph text. Example paragraph text. Example paragraph text. Example paragraph text. Example paragraph text.</p>

<img src="codexradar.jpg" alt="CodexRadar Logo">

</body>
</html> code-box

If the width is set to 100%, the image cannot be centered. alert-warning

Method : 2

If the image is inside a container element such as div, p or some other element, then we do it in the center with the help of text-align property. 

HTML code as follows:

<div class="center">
<img src="codexradar.jpg" alt="CodexRadar Logo">
</div>

<p class="center">
<img src="codexradar.jpg" alt="CodexRadar Logo">
</p> code-box

CSS code as follows:

<style>

.center {
text-align: center;
}

</style> code-box

Method : 3

In this method we will learn to center the image vertically and horizontally. To center the image vertically, we display the container as a table-cell and set the value middle of the verticle-align. To set the image horizontally, we set the value center of the text-align.

HTML code as follows:

<div class="container">
<img src="codexradar.jpg" alt="CodexRadar Logo">
</div> code-box

CSS code as follows:

<style>

.container {
display: table-cell;
vertical-align: middle;
 text-align: center;
height: 500px;
background: #f1f1f1;
}

</style> code-box

With the help of these methods, we can easily center the image. If there is any other method to center the image in future, then we will update its information in this post as well.

Summary

In this post we learn how to center an image with HTML and CSS. You try to make it yourself. I hope you make. If you face any problem, then comment and tell us. Keep visiting the blog to read more similar posts.

1 Comments

Post a Comment

Previous Post Next Post