Center Div Vertically And Horizontally Without Defined Height
I want to display a div in the centre of my page without having to define a set height for the element so that the height fits the content of the page dynamically. Is this possible
Solution 1:
You could do it by set top:50%; and transform: translateY(-50%); to .card
JSFiddle - DEMO or Full Screen View
CSS:
html, body {
    height:100%;
    margin: 0px;
}
.card {
    background-color: #1d1d1d;
    /* IE fallback */background-color: rgba(29, 29, 29, 0.95);
    color: #fff;
    padding: 30px35px;
    outline: 2px solid #3B3A37;
    outline-offset: -9px;
    width: 320px;
    position: relative;
    margin: 0 auto;
    top:50%;
    -webkit-transform: translateY(-50%);
    -ms-transform: translateY(-50%);
    -moz-transform: translateY(-50%);
    -o-transform: translateY(-50%);
    transform: translateY(-50%);
}
For more info:
Solution 2:
If you want a CSS only solution without specifying height:
- You can use css3 flexbox: - body { display:flex; align-items:center; }
- Or you can use the translate technique: - .card { position: absolute; top: 50%; left:50%; transform: translateX(-50%) translateY(-50%); /* other styles */ }
browser support:
Side note: You might need js fallbacks if you want to support old browsers
Post a Comment for "Center Div Vertically And Horizontally Without Defined Height"