Ways to Centre Image - HTML & CSS

As a Web Developer you must know about this.

ยท

2 min read

Ways to Centre Image - HTML & CSS

You must know about these ways as a developer. Few days ago, this question was asked by me on freeCodeCamp and I failed to answer these questions. Then I got to know about this. I thought to make an article on this topic. So, let's start...

Centering Image with CSS

  • Using Flex Property

  • Using Margin Property

  • Using Text Aling Property

Let's take an example first:

<body>
    <div class="main">
        <img src="user.png" alt="user png" class="img">
    </div>
</body>

Also adding CSS to div tag:

    <style>
        .main{
            height: 100vh;
            width: 100vw;
        }
    </style>

Here you can see that I have taken image in div tag. We all know that div is block level element. Since, we have taken div tag therefore we cover inline element in upcoming articles.

Using Flex Property

This property is very popular. So, what you to do is set display to flex. Using flex property i.e., justify-content. So, Let's do with practical:

.main{
    height: 100vh;
    width: 100vw;
}

Using Margin Property

We know that img tag is inline element, but after giving width and height then behaves like inline-block element. By using CSS let's set it to display as block because as inline element we can't apply this property therefore it's very important to apply. The set margin left and right to auto. Let's implement this:

.img{
    display: block;
    margin-left: auto;
    margin-right: auto;
}

Using Text Align Property

This property only works on block level elements and not inline elements. We have done img tag in block level element. Now add text align as center property on div tag. Let's do it practically:

.main{
    height: 100vh;
    width: 100vw;
    text-align: center;
}

So, friends that's it in this article. If you have any doubt, then It's my pleasure to answer that question. Thanks for reading ๐Ÿ“–. Have a Nice Day! ๐Ÿ‘

Did you find this article valuable?

Support Vaibhav Maurya by becoming a sponsor. Any amount is appreciated!

ย