How to vertically and horizontally center divs of unknown height

I tried using the flexbox method, the table method and some other methods of vertically centering divs of unknown height, but my div is not centered correctly. I want the centered div to be 50% of the width of the window or have a minimum width of 200 pixels.

.content {
  background-color: violet;
  min-width: 200px;
  width: 50%;
  margin-left: auto;
  margin-right: auto;
  box-shadow: 0px 1px 7px 1px rgba(0, 0, 0, 1);
}

.outer-container {
  display: table;
  width: 100%;
  background-color: violet;
}

.container {
  display: table-cell;
  text-align: center;
  vertical-align: middle;
}
<body>
  <div class="outer-container">
    <div class="container">

      <div class="content">
        <div class="title-class">
          Hello there
        </div>
      </div>
    </div>
  </div>
</body>
Run codeHide result
+2
source share
1 answer

Using flexbox, all the code is needed here:

HTML

<div class="container">
    <div class="content">
        <div class="title-class">Hello there</div>
    </div>
</div>

CSS

html, body { height: 100%; }

.container {
    display: flex;
    justify-content: center;
    align-items: center;
    background-color: violet;
    height: 100%;
}

.content {
    background-color: violet;
    width: 50%;
    text-align: center;
    box-shadow: 0px 1px 7px 1px rgba(0, 0, 0, 1);

}

Demo

Alternatively, the table method is used here:

+4
source

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


All Articles