Hello there!!! In this post you will learn the solution to one of the most sought after problems for web designers: Centering a div both horizontally, and vertically
Here is the end result:Here is the youtube tutorial:
So let's get our hands to work
Step 1: Initialize
So this is just the basic stuff of every HTML page: DOCTYPE, html, head and body tags. Just fire up your code editor and paste the following code:
1 2 3 4 5 6 7 8 9 10 11 | <html> <head> <title>Center element</title> <style> </style> </head> <body> </body> </html> |
This just creates an empty HTML document
Step 2: Elements
So, for this tutorial, we are just creating a parent div with a child div in it which we will center shortly. For now, enter the following code in the body tag:
1 2 3 4 5 | <div class="parent"> <div class="child"> </div> </div> |
This creates two divs, one inside the other. But you will see no changes since we have not styled it yet.
Step 3: Styling
Now, we will style the child tag so it is visible. Paste the following code inside the style tag and refresh your browser:
1 2 3 4 5 6 | .range { width: 100px; height: 100px; border-radius: 50%; background-color: #4deb77; } |
This changes the child div tio a 100*100 circle
Step 4: Centering
Now we will horizontally and vertically center our div at the center of the page. To do this, paste the following code in your style tag:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | html, body { height: 100%; width: 100%; padding: 0; margin: 0; } .parent { width: 100%; height: 100%; padding: 0; margin: 0; display: flex; align-items: center; justify-content: center; } |
Now, here comes the complex part. What this does is, it first assigns a width and height to the full width of the page, and then makes padding and margin 0 so as to avoud the unnecessary scrollbar. After this, we make the parent container to display as flex, instead of the usual block. You can Google to know more about flex. Then, we use align-items: center to vertically align the child div and justify-content: center to horizontally center the div.
Hope this tutorial helped you. If you want other CSS/HTML/JS/JQuery/PHP/Vue tutorials, drop a comment and I will look into it.
Final code:
Here is the final code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 | <!DOCTYPE html> <html> <head> <title>Center element</title> <style> html, body { width: 100%; height: 100%; padding: 0; margin: 0%; } .parent { width: 100%; height: 100%; display: flex; align-items: center; justify-content: center; } .object { height: 100px; width: 100px; border-radius: 50%; background-color: #4deb77; } </style> </head> <body> <div class="parent"> <div class="object"> </div> </div> </body> </html> |
Comments
Post a Comment