有几个技巧可以在 div 的中心显示内容或图像。有些答案真的很好,我也完全同意这些。
CSS中的绝对水平和垂直居中
http://www.css-jquery-design.com/2013/12/css-techniques-absolute-horizontal-and-vertical-centering-in-css/
有10 多种技术示例。现在由您决定您喜欢哪个。
毫无疑问,display:table; display:table-Cell
是一个更好的把戏。
一些好的技巧如下:
技巧 1 - 通过使用display:table; display:table-cell
HTML
<div class="Center-Container is-Table">
<div class="Table-Cell">
<div class="Center-Block">
CONTENT
</div>
</div>
</div>
CSS 代码
.Center-Container.is-Table { display: table; }
.is-Table .Table-Cell {
display: table-cell;
vertical-align: middle;
}
.is-Table .Center-Block {
width: 50%;
margin: 0 auto;
}
技巧 2 - 通过使用display:inline-block
HTML
<div class="Center-Container is-Inline">
<div class="Center-Block">
CONTENT
</div>
</div>
CSS 代码
.Center-Container.is-Inline {
text-align: center;
overflow: auto;
}
.Center-Container.is-Inline:after,
.is-Inline .Center-Block {
display: inline-block;
vertical-align: middle;
}
.Center-Container.is-Inline:after {
content: '';
height: 100%;
margin-left: -0.25em; /* To offset spacing. May vary by font */
}
.is-Inline .Center-Block {
max-width: 99%; /* Prevents issues with long content causes the content block to be pushed to the top */
/* max-width: calc(100% - 0.25em) /* Only for Internet Explorer 9+ */
}
技巧 3 - 通过使用position:relative;position:absolute
<div style="position: relative; background: #ddd; border: 1px solid #ddd; height: 250px;">
<div style="width: 50%; height: 60%; overflow: auto; margin: auto; position: absolute; top: 0; left: 0; bottom: 0; right: 0; background: #ccc; text-align: center;">
<h4>ABSOLUTE CENTER, <br/>
WITHIN CONTAINER.</h4>
<p>This box is absolutely centered, horizontally and vertically, within its container</p>
</div>
</div>