how to center a div in html5 and css3
centring div in css is not easy specially when you start coding , because css don't offer us a direct function or properties to center a div , so i decided in this mini tutorial to show you the most easyest way to put your div in the center of your page , so let's begin .
1. create your html part
first , we have to create the html file :
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<div class="center">
</div>
</body>
</html>
<html>
<head>
<title></title>
</head>
<body>
<div class="center">
</div>
</body>
</html>
2. add style
now that our element was created , all what we have to do is to give him a widht and a heigh and a backgroud color
width:500px;
height:300px;
backgroundcolor:#f44336;
3.center your element
now let's start to center the div , all what you have to do is add these line of code
position:absolute;
left:50%;
top:50%;
transform : translate(-50%,-50%);
so i will explain what i did .
(position absolute) : this is mean that our elemtn is relative to the parent element , let me reminds you that te positon start from the top left corner of an element that have coordinate (0,0) so when we says position absolute and left :0; this is mean that the top left corner of an element will be on the left , when i used left:50%; and top:50%; this is mean that i puted the origin point of the element on the middle of the parent element ( that is body in our case ) .
ti put the center of the element at the middle of the parent element i used translate(x,y)
that transalte the element by 50% left that's mean the half of it's width and 50% top , that's mean the half of it's height .
now you know how to center your element using html and css , i hope you liked this mini tutorial if there is some point that are not clear please tell me in the comment and i will answer you , thank you for reading
how to center a div in html5 and css3
Reviewed by Medics
on
February 03, 2019
Rating:
No comments: