How to center align an image or div using CSS

Introduction: In this article I am going to explain how to center align an image or the div element with the help of CSS.  


Description: Sometimes it is required to show image or div element in the center of the page. We can simply align them using CSS as shown below in example.

Implementation: Let’s see by an example.

<html>
<head>
    <style>
        .center-div {
            margin: auto;
            width: 50%;
            border: 2px solid orange;
            padding: 10px;
        }

        .center-img {
            display: block;
            margin-left: auto;
            margin-right: auto;
        }
    </style>
</head>
<body>

    <div style="background-color:#f0f1f3">
        <div style='width:150px;' class='center-div'>Center aligned div</div><br />

        <img src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj_0ieUzgku7fJVmj2ITTE5wK7LTxndqVSEEyYujXce0zYncwxAgQw0sfn-VzSb1FA2fYNKtRG2K4RwXlupLlpIfEVLOk1UOymBo9F7JPYk2Lr0eiaZ683ygp9Uoklgx5Wf_dquDygeLvXE/s113/Lalit+Raghuvanshi.jpg"
             alt="Lalit Raghuvanshi" class='center-img' style="width:120px">
    </div>
</body>
</html>

Explanation: We have applied the CSS class 'center-div’ on div element and 'center-img' class on image element that we created to align them to the center. 

To center a div element; settings marginauto; plays an important role and to center an image; settings  margin-leftauto; margin-rightautodisplayblockare necessary.

Now over to you:
A blog is nothing without reader's feedback and comments. So please provide your valuable feedback so that i can make this blog better and If you like my work; you can appreciate by leaving your comments, hitting Facebook like button, following on Google+, Twitter, Linked in and Pinterest, stumbling my posts on stumble upon and subscribing for receiving free updates directly to your inbox . Stay tuned and stay connected for more technical updates.
Previous
Next Post »

If you have any question about any post, Feel free to ask.You can simply drop a comment below post or contact via Contact Us form. Your feedback and suggestions will be highly appreciated. Also try to leave comments from your account not from the anonymous account so that i can respond to you easily..