中心与表格单元格对齐

Ste*_*is_ 35 html css

我正在尝试使用table-cell方式将div垂直和水平居中.

它使用以下代码时工作:

div {
    display: table;
}
.logo {
    display: table-cell;
    position: absolute;
    vertical-align: middle;
    left: 0;
    right: 0;
    bottom: 0;
    top: 0;
    margin: auto;
}
Run Code Online (Sandbox Code Playgroud)

但我宁愿换.logo在另一个名为DIV .center喜欢这里的jsfiddle,但由于某些原因,虽然它工作在的jsfiddle,它不是为我工作在我的网站.

Mar*_*det 46

这是一个很好的起点.

HTML:

<div class="containing-table">
    <div class="centre-align">
        <div class="content"></div>
    </div>
</div>
Run Code Online (Sandbox Code Playgroud)

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 */
}
Run Code Online (Sandbox Code Playgroud)

请参阅演示:http://jsfiddle.net/audetwebdesign/jSVyY/

.containing-table.centre-align(表格单元格)建立宽度和高度上下文.

您可以根据需要申请text-alignvertical-align更改.centre-align.

请注意,如果要使用text-align属性水平居中,则.content需要使用display: inline-block.


Lou*_*eda 24

使用flexbox会更容易.使用flexbox将不允许您指定内容的高度,并可以自动调整其包含的高度.

DEMO

这是演示的要点

.container{

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

}
Run Code Online (Sandbox Code Playgroud)

HTML

<div class="container">
  <div class='content'> //you can size this anyway you want
    put anything you want here,
  </div>
</div>
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

  • OP 正在寻找显示的答案:“table-cell”。 (2认同)