
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
Center Div Tag Using CSS
For web layout, it's essential to center a <div> in CSS. The task of centering a div should be encountered by every developer at some point in their career, if not every day. Everybody has a handy approach, but it can occasionally be annoying for beginners.
The visual appeal and usability of your web design are improved by these CSS approaches, which guarantee dynamic and smooth centering. Let's look them one by one before that let's have a quick view on the div tag.
HTML div tag
In an HTML, the <div> tag is used as a division or section. The HTML <div> tag is used to group HTML elements, which are subsequently given a container and given a CSS or JavaScript style. The class or id attribute makes it simple to decorate the div tag.
Syntax
Following is the syntax for HTML div tag −
<div>......</div>
Example
Let's look at the following example, where we are going to center div using the flexbox.
<!DOCTYPE html> <html> <head> <style> .tp { height: 300px; background: #D5F5E3; display: flex; align-items: center; color: #DE3163; font-family: verdana; justify-content: center; } .tp1 { background-color: #CCD1D1; width: 150px; height: 50px; } </style> </head> <body> <div class="tp"> <div class="tp1">WELCOME TO TUTORIALSPOINT</div> </div> </body> </html>
When we run the above code, it will generate an output consisting of the div boxes, out of which one is centered and displayed on the webpage.
Example
Considering another scenario, where we are going to use the CSS Justify-Content Property
<!DOCTYPE html> <html> <head> <style> body { background-color: #D5F5E3; } .tp { margin: 100px; border: 1px solid #17202A; display: flex; justify-content: center; font-family: verdana; color: #DE3163; } </style> </head> <body> <div class="tp"> <p>MS Dhoni Lifts The WorldCup</p> </div> </body> </html>
On running the above code, the output window will pop up, displaying the div text centered on the webpage.
Example
In the following example, we are going to center the div using the grid.
<!DOCTYPE html> <html> <head> <style> body { background-color: #E8DAEF; } section { font-family: verdana; color: #DE3163; font-size: 50px; height: 450px; display: grid; place-items: center; } .tp { background-color: yellow; } </style> </head> <body> <section> <div class="tp">WELCOME</div> </section> </body> </html>
When we run the above code, it will generate an output consisting of the text aligned at the center displayed on the webpage.