Tuesday, October 2, 2018

How to center div/something both in horizontally and vertically

We know that the content inside <body> and </body> tags is visible in webpages. Lets create a div inside the body tags with a class container using the lines <div class="container"> and </div>. And there we will take a line "Test Content" inside the div with h1 header tag. So the codes will look like below...


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>CSS Tricks</title>
</head>
<body>
    <div class="container">
        <h1>Test Content</h1>
    </div>
</body>
</html>


Now we will create a stylesheet in the same directory named style.css and write the following codes below in it.

.container {
    width: 960px;
    height: 700px;
    border: 1px solid #d7d7d7;
}

Then we will add the stylesheet using the line <link rel="stylesheet" href="style.css"> , this line should be before the closing </head> tag. Now we will see something like below the image when we will browse the webpage.

Now add the css margin: 0 auto; to centre the container. The webpage will look like below the image.
We know the container height is 700px , so we can vertically center the text if we want to use the css line-height: 700px; But there is a problem if there are more than one tag/content. The line height will work for both/all of them. That's why there will be a gap of the provided line height between those content.

We can simply centre the text both vertically and horizontally just using four lines of css codes. We will use display: table; for the .container class and will use display: table-cell; vertical-align: middle; and text-align: center;
So, now the complete css codes will look like below...

.container { 
 width: 960px;
 height: 700px;
 border: 1px solid #d7d7d7;
 margin: 0 auto; display: table;


h1 {
 display: table-cell;
 vertical-align: middle;
 text-align: center; 
}