我正在尝试使用表格单元格方式使 div 垂直和水平居中。
当我使用以下代码时它有效:
div {
display: table;
}
.logo {
display: table-cell;
position: absolute;
vertical-align: middle;
left: 0;
right: 0;
bottom: 0;
top: 0;
margin: auto;
}
但我宁愿将 .logo
包装在另一个名为 .center
的 div 中,就像这里 JSFiddle , 但出于某种原因,虽然它在 JSFiddle 中有效,但在我的网站上对我不起作用。
最佳答案
这是一个很好的起点。
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 */
}
参见演示:http://jsfiddle.net/audetwebdesign/jSVyY/
.containing-table
为 .centre-align
(表格单元格)建立宽度和高度上下文。
您可以根据需要应用 text-align
和 vertical-align
来更改 .centre-align
。
请注意,.content
需要使用 display: inline-block
才能使用 text-align 属性水平居中。
关于html - 与表格单元格居中对齐,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19184052/