4

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

.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>
Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701
Autumn
  • 223
  • 3
  • 15

1 Answers1

6

Using a flexbox, here's all the code you need:

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

As an alternative, here's the table method:

Community
  • 1
  • 1
Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701
  • It looks like when the div reaches a certain height, the top of the div gets hidden: https://jsfiddle.net/prettysweet/bsxng9g8/ – Autumn Sep 02 '15 at 01:41
  • 1
    @Autumn, yes, that's a known issue. For a solution see [**here**](http://stackoverflow.com/a/33856609/3597276) (refer to Box #56) and [**here**](http://stackoverflow.com/a/33455342/3597276). – Michael Benjamin Dec 18 '15 at 00:58