Html 与表格单元格居中对齐

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19184052/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 14:06:33  来源:igfitidea点击:

Center align with table-cell

htmlcss

提问by Steven_Harris_

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

我正在尝试使用表格单元格方式将 div 垂直和水平居中。

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 .logoin another div called .centerlike here JSFiddle, but for some reason, although it works in JSFiddle, it isn't working for me on my site.

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

回答by Marc Audet

Here is a good starting point.

这是一个很好的起点。

HTML:

HTML:

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

CSS:

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/

见演示:http: //jsfiddle.net/audetwebdesign/jSVyY/

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

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

You can apply text-alignand vertical-alignto alter .centre-alignas needed.

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

Note that .contentneeds to use display: inline-blockif it is to be centered horizontally using the text-align property.

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

回答by Louie Almeda

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.

使用 flexbox 会更容易做到这一点。使用 flexbox 可以让你不指定内容的高度,并且可以根据它包含的高度自动调整。

DEMO

演示

here's the gist of the demo

这是演示的要点

.container{

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

}

html

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

在此处输入图片说明