I'm sure we have all been there! Starting web development and you are tasked with placing an item in the center of the screen or box. Searching Stack Overflow and the internet will give you many valid ways to place this div in the center, but for me, these have been the easiest to use and remember.
Using the display property, we can break down the behavior of the elements within the body or container you are trying to center. When setting the display property, we want to put the CSS code inside the element that contains the div we are looking to center, not the div itself. In our recommended styles, we will use both the flex and grid displays, but they will both satisfy the need to center your div.
Display Flex :
.wrapper{
display: flex;
justify-content: center;
align-items: center;
}
The first way I center div's is using a flex display with the properties justify-content and align-items, both set to center. justify-content will handle the centering of the x-axis, while align-items will take care of the y-axis.
Display Grid :
.wrapper{
display: grid;
place-items: center;
}
My other preferred way to center div's is using a grid display. This one is even easier to commit to memory as after you set display to grid, you just need to set place-items to center. This will both horizontally and vertically center your div inside the element.
Top comments (0)