![]() This is one of the common methods followed since the birth of 'CSS Positioning'. I've personally faced some inconsistencies while trying this method, so I always add extra properties to center the elements. All we have to do is define 'margin: 0 auto' style to the child container. Yet another old school method works like a charm in all the browsers. We make the child container's position absolute to the parent container and move the child container to 50% from the top and left of the parent. This is one of the old school methods we follow to center elements on a page. Method 3: Using CSS Positioning and CSS transform We give the parent 'display: grid' and 'place-items: center' and there you go, things get super centered.ī) Using 'justify and align-self', we provide the parent container with 'display: grid' property, and the main properties are given to the child container - 'align-self'(vertically placement) and 'justify-self'(horizontal placement) props are given center as value. Yet again, these properties are exclusive to CSS Grid.Ī) Using place-items, we provide the rules to the parent, and it alone does the magic. First, using 'place-items' properties and second is by using 'align and justify self'. Using CSS Grid, we can achieve our goal in two ways. One glitch to make this work is by providing a fixed width and height to the parent. These properties come with Flex specifications. We define the parent with display: flex property along with justify-content(horizontal placement by default) and align-items(vertical placement by default) center. In this trick, all the CSS properties are defined under the parent container. I wanted this technique to be on top since it's my favorite of all. In this article, I have compiled a list of different CSS tricks to center a div horizontally and vertically center on a page, choose a trick or two, and make it your favorite. We all have our handy technique but for beginners, it might be frustrating at times. Every developer should have come across this task of centering a div in their lifetime at least once or every single day.
0 Comments
Leave a Reply. |