How to Center a div😂
Shubham Tiwari
Posted on January 25, 2022
Hello guys today i am going to show you how to center a div in HTML🤣
Lets get started...
HTML PART -
<div class="center">
<h1>Hello Center Div</h1>
<img src="IMG_20210105_092229.jpg"
width="300px" height="300px"/>
</div>
- So this is the div element with the class named "center" and inside id , we have two elements an h1 tag and an image, we are going to center these elements inside the div.
1. Using text-align -
- The first property is text-align, if we use this property on our div element then the elements inside div will be horizontally centered centered.
.center{
text-align: center;
}
Output -
2. Using flex to center the div vertically -
.center{
display: flex;
flex-direction: column;
align-items: center;
}
- First we make the div flexbox usig display:flex
- Then make the direction of flex as column so that the items will stack in a column instead of row.
- Then we centered the div vertically using align-items:center.
Output -
3. Using flex to center the div horizonatally
.center{
display: flex;
justify-content: center;
}
- First we make the div flexbox using display:flex.
- Then we center the elements horizontally using justify-content property.
Output -
4. Using Grid system
.center{
display: grid;
justify-content: center;
}
- First we make the div a grid using display:grid.
- Then we center the element horizontally using justify-content property.
Output-
5. Using Grid to Align items horizontally and vertically.
.center{
height: 100%;
display: grid;
justify-content: center;
align-items: center;
}
- To center the element inside div horizontally we have used justify-content property and to center it vertically we have used align-items property, So the element inside div is now centered both horizontally and vertically.
Output -
6. Using Place-content -
.center{
height: 100%;
display: grid;
place-content: center;
}
- To center the element inside div both horizontally and vertically we can also use the place-content property , it center element both horizontally and vertically with one line of code.
Output -
Thats it for this post.
THANK YOU FOR READING THIS POST AND IF YOU FIND ANY MISTAKE OR WANTS TO GIVE ANY SUGGESTION , PLEASE MENTION IT IN THE COMMENT SECTION.
^^You can help me by some donation at the link below Thank you👇👇 ^^
☕ --> https://www.buymeacoffee.com/waaduheck <--
Also check these posts as well
https://dev.to/shubhamtiwari909/higher-order-function-in-javascript-1i5h/edit
https://dev.to/shubhamtiwari909/arrow-function-in-javascript-46gd
https://dev.to/shubhamtiwari909/javascript-oop-2-inheritance--44c2
💖 💪 🙅 🚩
Shubham Tiwari
Posted on January 25, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.