If I have one thing that I like to share with CSS, it is MY FAVORITE WAY OF CENTRAL USE IN CURRENT-BASED BOTH FACES !!!
Advantages of this method :
- Fully compatible with browsers that people actually use
- No need for tables
- Very reusable to center any other elements within their parent
- Placement of parents and children with dynamic (variable) sizes!
I always do this using 2 classes: one to indicate the parent element whose contents will be centered ( .centered-wrapper ), and the second to indicate which child element of the parent is centered ( .centered-content ). This 2nd class is useful when the parent has several children, but only 1 needs to be centered). In this case, the body will be .centered-wrapper , and the inner div will be .centered-content .
<html> <head>...</head> <body class="centered-wrapper"> <div class="centered-content">...</div> </body> </html>
The idea of centering now is to make .centered-content an inline-block . This will make it easy to facilitate horizontal centering, text-align: center; , and also allows vertical centering, as you will see.
.centered-wrapper { position: relative; text-align: center; } .centered-wrapper:before { content: ""; position: relative; display: inline-block; width: 0; height: 100%; vertical-align: middle; } .centered-content { display: inline-block; vertical-align: middle; }
This gives you 2 really reusable classes to center any child inside any parent! Just add .centered-wrapper and .centered-content classes.
So what's with this element :before ? This facilitates vertical-align: middle; and necessary, because vertical alignment does not apply to the height of the parent - vertical alignment relative to the height of the highest brother !!!. Therefore, ensuring that there is a brother whose height is the parent height (height 100%, width 0 to make it invisible), we know that vertical alignment will refer to the parent height.
Last: you have to make sure your html and body tags are the size of the window, so centering on them is the same as centering the browser!
html, body { width: 100%; height: 100%; padding: 0; margin: 0; }
Fiddle: https://jsfiddle.net/gershy/g121g72a/
Gershom Maes Jan 27 '16 at 20:07 2016-01-27 20:07
source share