• 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%);
Смотрите видео Perfectly Centering DIVs Horizontally and Vertically Every Time Using CSS3 онлайн без регистрации, длительностью часов минут секунд в хорошем качестве. Это видео добавил пользователь Arjun Khara 20 Март 2016, не забудьте поделиться им ссылкой с друзьями и знакомыми, на нашем сайте его посмотрели 35,185 раз и оно понравилось 946 людям.