+ 7
How can I center my div container horizontally and vertically?
I have been struggling with placing my grid contents [direct children of my grid container] at the center of the body of my page. If apply place-items: center on my container to center it horizontally and vertically, it does not work. Please I need you advise. .grid-container{ height: 600px; width: 800px; margin: 0 auto; display: grid; grid-template-columns: repeat(2, 1fr); grid-template-rows: repeat(2, 200px); place-items: center; } the above code could not give me what I'm looking for. Who can help
13 Antworten
+ 2
The grid items just look at its parent, the grid container.
Check this example.
https://code.sololearn.com/WNf583stzFL2/?ref=app
its meant for desktop based on your code. in phone looks bad.
+ 1
Hello. You can center the element horizontally, in the <body> element.
e.g.
div {
height: 400px;
width: 400px;
border: 2px solid red;
margin: auto;
}
******
<body>
<div> Your content </div>
</body>
If that's what you mean...
+ 1
Lamron thanks.
But what if I don't what to use a width that is equal to the height?
Something like:
height: 600px;
width: 800px;
+ 1
DN Josh , that would be fine. I just made a square with a border - so <div> element could be seen on the page.
The key part to it is **margin: auto;**
+ 1
Arturop thabks for the visual aid.
But I noticed that your grid container is not situated at the very center of the body since you gave height 100vh
+ 1
DN Josh in sololearn app it doesnt look good. I use pc
+ 1
DN Josh I fixed it now, i just modified the size of the container and template rows and colums
+ 1
Arturop perfect!
But can you make it responsive in mobile?
+ 1
I belive I can, it just depends on what is the desire output. Here im just giving an example of centering content
+ 1
I read an article about centering a div using grid and it also talked about making the body height 100vh. Is it compulsory? Can't we use another value?
+ 1
To vertically align an item, the parent should be bigger.
The initial value of height is auto, it will just be as big as its content.
Thats why we set it to 100vh cuz we know the content is or will be smaller.
+ 1
Yes you can set the height to a different value, but if you use percentage, it will try to take the parent height as reference and the height of html is auto, so again you need to define a height for html
0
place-content:center;
------------or------------
justify-content:center;