• Title: Vertically and Horizontally Centered Divs
• Tutorial sponsor: Quantico Singapore Copywriting and Content Marketing Courses (https://www.qc.sg)
• Music: End of Summer and Pas de Deux
• Author: Arjun Khara
Here's a simple and effective way to always have your divs centered vertically and horizontally, using the CSS3 transform: translate( ); property-value pair. Here's the code snippet, including browser fallbacks:
.centereddiv{
background-color: #000;
position: absolute;
width: 650px;
height: 100px;
top: 50%;
left: 50%;
-webkit-transform: translate(-50%, -50%);
-moz-transform: translate(-50%, -50%);
-o-transform: translate(-50%, -50%);
-ms-transform: translate(-50%, -50%);
transform: translate(-50%, -50%);
Centering is a popular issue in CSS and gets a lot of attention just because it’s central to page layouts. we can simply use the property-value pair called Transform: Translate
Translate shifts an element on a page on the X and Y axes and it accepts all values, including percentage and pixels. We simply put:
transform: translate (-50%, -50%). That’s it.
Now when we change the dimensions of the div to anything we want. You can see the div always remains in the center, because the browser is compensating for any width and height dimensions using the translate property. It’s really easy.
It’s good practice to implement browser-fallback properties. So in addition to your code, you would simply add the browser prefix for translate like this.
-webkit-transform: translate(-50%, -50%);
-moz-transform: translate(-50%, -50%);
-o-transform: translate(-50%, -50%);
-ms-transform: translate(-50%, -50%);
transform: translate(-50%, -50%);
Watch video Perfectly Centering DIVs Horizontally and Vertically Every Time Using CSS3 online without registration, duration hours minute second in high quality. This video was added by user Arjun Khara 20 March 2016, don't forget to share it with your friends and acquaintances, it has been viewed on our site 35,185 once and liked it 946 people.