Position Absolute - Translate
Lesson 3 of 9 in Coddy's How to Center Div or Text using CSS course.
To center a div vertically and horizontally we can you the position CSS property with the combination of translate.
To start set position: absolute; the parent div must contain position: relative; so that the child will be relative to parent.
.parent {
position: relative;
}
.child {
position: absolute;
top: 50%;
left: 50%;
}The above will position the child div almost at the middle it will take 50% of the parent height from the top size and 50% of the parent width from the left size.
Try it by yourself to see how it looks!
To center the child completely, move him using the CSS property transform: translate(-50%, -50%);, it will move the div relative to the sizes of his own, so, 50% of his height to the top direction, and 50% of his width to the left direction.
Try playing with the direction 50%, -50%, 30%, to catch the directions.
Challenge
EasyPosition the child in the center of the parent using position absolute and translate!
Don't change the size of the div.
Try it yourself
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="parent">
<div class="child"/>
</div>
</body>
</html>All lessons in How to Center Div or Text using CSS
1Introduction
What is this course?2Center Div
Margin AutoPosition Absolute - TranslatePosition Absolute - MarginFlex BoxRecap Challenge