Center div vertically and horizontally without a certain height

I want to display a div in the center of my page without having to determine the height of the set for the element so that the height matches the content of the page dynamically. Is it possible? I am open to using JS / jQuery solutions if they have graceful backups, but I would prefer a clean CSS solution.

Here is my current code, it will center the div, but I have to include the height.

HTML

<div class="card">Lorem ipsum dolor sit amet, minim molestie argumentum est at, pri legere torquatos instructior ex. Vis id odio atomorum oportere, quem modo fabellas sit at, dicat semper est ne. Apeirian detraxit pri eu. No solum accusam has. Ius ne harum mundi clita, eu pro tation audiam. </div> 

CSS

 .card { background-color: #1d1d1d; /* IE fallback */ background-color: rgba(29, 29, 29, 0.95); color: #fff; display: inline-block; margin: auto; position: absolute; bottom: 0; top: 0; left: 0; right: 0; padding: 30px 35px; outline: 2px solid #3B3A37; outline-offset: -9px; width: 320px; height: 350px; /*margin: 0 auto;*/ } 

Script Link

This question differs from the previous ones because of the time it was asked, a similar question on which it was compared is dated 2011, in which much has changed, and new functions have been added to CSS3 that could perform better.

+6
source share
2 answers

You can do this by setting top:50%; and transform: translateY(-50%); in .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: 30px 35px; 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 information:

+8
source

If you want to use only CSS solution without specifying height:

  • You can use css3 flexbox :

     body { display:flex; align-items:center; } 

    Updated Fiddle

  • Or you can use the translation technique:

     .card { position: absolute; top: 50%; left:50%; transform: translateX(-50%) translateY(-50%); /* other styles */ } 

    Updated Fiddle

browser support:

Side note. You might need js backups if you want to support older browsers.

+4
source

Source: https://habr.com/ru/post/975257/


All Articles