Skip to content
Y
yTube.SITE v8.0.4
media / worlds / tools / internet oddities
YouTube / video information

Perfectly Centering DIVs Horizontally and Vertically Every Time Using CSS3

Video information, playback and saved actions.

Perfectly Centering DIVs Horizontally and Vertically Every Time Using CSS3

Description: • 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%); Close description
      
Videos related to "Perfectly Centering DIVs Horizontally and Vertically Every Time Using CSS3"