41. CSS – Align Elements using Transform Property

41. CSS – Align Elements using Transform Property


Hello everyone and welcome back. In today’s video I will show you another way to align content in horizontal center vertical center and center of the div. We will be using a combination of position absolute and translate. So let’s give it a try. Let’s bring about good editor. All right let’s say we have to move this div in the center horizontally so we could simply use position absolute and by default it’ll be relative to the main body. Now to move it to the center we could do left 50 percent let’s say there are now as you can see this there was starting from the center of the screen but it itself is not in the center. So for that what we can do is we get translated towards the left by harmful effects with. So let’s give that a try so transform translate X so do move it towards the left hand side. We can give a negative value C minus 50 percent. So this will move are diff by 50 percent of the way towards the left. Let’s say that and as you can see now our div is in the center of the screen horizontally. Similarly said you wanted to align it in the center vertically. So let’s just common this let’s say top 50 percent let’s save it. Let’s remove this margin. And as you can see our element is starting from the center of the screen vertically so again to make it in the center. We can translate our element 50 percent of the height towards the top. So let’s try that. So transform translate y and to move it towards the top we can use a negative value so negative 15 percent 50 percent let’s say that. Now as you can see it is in the center would eagerly. Now to move it in the center of the div we can use both the properties. If I just uncommon this unsaved and as you can see it is in the center horizontally but not what we believe. So why is that. Because this first transform properties being overwritten by the second one not to give both. We can give it like this. So translate Y minus 50 percent or we could simply use translate an insight that we could do minus 50 percent and minus 50 percent let’s say that. Now as you can see our element is in the center of the div and that’s how we use position absolute and transform to align contained in the center. That’s all for today guys. If there is something that you did not understand feel free to drop a comment and we will discuss it. See you in the next video by Antigua.