How can I vertically and horizontally center a div in a larger div?

How to horizontally center a <div> in another <div>? I managed to center horizontally using the style from the accepted answer. How can I also center it vertically? The inner div has an unknown height.

+3
source share
2 answers

From: http://www.jakpsatweb.cz/css/css-vertical-center-solution.html

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html>
<head>
  <title>Universal vertical center with CSS</title>
  <style>
    .greenBorder {border: 1px solid green;} /* just borders to see it */
  </style>
</head>

<body>
  <div class="greenBorder" style="display: table; height: 400px; #position: relative; overflow: hidden;">
    <div style=" #position: absolute; #top: 50%;display: table-cell; vertical-align: middle;">
      <div class="greenBorder" style=" #position: relative; #top: -50%">
        any text<br>
        any height<br>
        any content, for example generated from DB<br>
        everything is vertically centered
      </div>
    </div>
  </div>
</body>
</html>
+7
source

Here's a cool technique for centering the box both vertically and horizontally:

Container

  • must have display: table;

Inner container

  • must have display: table-cell;
  • must have vertical-align: middle;
  • must have text-align: center;

Content field

  • must have display: inline-block;
  • , . text-align: left; text-align: right;, ,

, , !

.

Demo

body {
    margin : 0;
}

.outer-container {
    position : absolute;
    display: table;
    width: 100%; /* This could be ANY width */
    height: 100%; /* This could be ANY height */
    background: #ccc;
}

.inner-container {
    display: table-cell;
    vertical-align: middle;
    text-align: center;
}

.centered-content {
    display: inline-block;
    text-align: left;
    background: #fff;
    padding : 20px;
    border : 1px solid #000;
}
<div class="outer-container">
   <div class="inner-container">
     <div class="centered-content">
        <p>You can put anything here</p>
        <p>Yes, really anything!</p>
     </div>
   </div>
</div>

. !

0

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


All Articles