Center align with table-cell

HtmlCss

Html Problem Overview


I'm trying to use the table-cell way to center a div vertically and horizontally.

It works when I use the following code:

div {
  display: table;
}
.logo {
  display: table-cell;
  position: absolute;
  vertical-align: middle;
  left: 0;
  right: 0;
  bottom: 0;
  top: 0;
  margin: auto;
}

But I'd rather wrap .logo in another div called .center like here JSFiddle, but for some reason, although it works in JSFiddle, it isn't working for me on my site.

Html Solutions


Solution 1 - Html

Here is a good starting point.

HTML:

<div class="containing-table">
    <div class="centre-align">
        <div class="content"></div>
    </div>
</div>

CSS:

.containing-table {
    display: table;
    width: 100%;
    height: 400px; /* for demo only */
    border: 1px dotted blue;
}
.centre-align {
    padding: 10px;
    border: 1px dashed gray;
    display: table-cell;
    text-align: center;
    vertical-align: middle;
}
.content {
    width: 50px;
    height: 50px;
    background-color: red;
    display: inline-block;
    vertical-align: top; /* Removes the extra white space below the baseline */
}

See demo at: http://jsfiddle.net/audetwebdesign/jSVyY/

.containing-table establishes the width and height context for .centre-align (the table-cell).

You can apply text-align and vertical-align to alter .centre-align as needed.

Note that .content needs to use display: inline-block if it is to be centered horizontally using the text-align property.

Solution 2 - Html

This would be easier to do with flexbox. Using flexbox will let you not to specify the height of your content and can adjust automatically on the height it contains.

DEMO

here's the gist of the demo

.container{

  display: flex;
  height: 100%;
  justify-content: center;
  align-items: center;

}

html

<div class="container">
  <div class='content'> //you can size this anyway you want
    put anything you want here,
  </div>
</div>

enter image description here

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSteven_Harris_View Question on Stackoverflow
Solution 1 - HtmlMarc AudetView Answer on Stackoverflow
Solution 2 - HtmlLouie AlmedaView Answer on Stackoverflow