vertically-align
相对于元素维度的最佳方法是什么?截至目前,我只知道vertical-align:middle;
在<tr>
内工作得很好。
我是否有任何其他方法可以在程序上实现这一目标?
答案 0 :(得分:4)
以下是3种非常好的技术,用于将容器中的子项垂直居中 - 即使您不知道子元素的高度。前2个来自this CSS-tricks article
标记(适用于所有方法):
<div class="block">
<div class="centered">
Some text
</div>
</div>
CSS:
/* This parent can be any width and height */
.block {
display: table;
width: 100%;
background: orange;
height: 300px;
}
.centered {
display: table-cell;
text-align: center;
vertical-align: middle;
background: pink;
}
<强> CSS:强>
/* This parent can be any width and height */
.block {
text-align: center;
background: orange;
height: 300px;
}
/* The ghost, nudged to maintain perfect centering */
.block:before {
content: '';
display: inline-block;
height: 100%;
vertical-align: middle;
margin-right: -0.25em; /* Adjusts for spacing */
}
/* The element to be centered, can
also be of any width and height */
.centered {
display: inline-block;
vertical-align: middle;
width: 300px;
background: pink;
}
(相关)CSS:
.block {
background: orange;
height: 300px;
display: flex;
align-items: center;
}
答案 1 :(得分:0)
CSS Tricks的这个article是您开始的好地方。它以明确简洁的方式覆盖了vertical-align
可以拥有的每个值以及每个值的不同用途。
以下是选项:
vertical-align: baseline /* keyword values */
vertical-align: sub
vertical-align: super
vertical-align: text-top
vertical-align: text-bottom
vertical-align: middle
vertical-align: top
vertical-align: bottom
以下是表格单元格的有效选项:
baseline (and sub, super, text-top, text-bottom, <length>, and <percentage>)
Align the baseline of the cell with the baseline of all other cells in the row that are baseline-aligned.
top
Align the top padding edge of the cell with the top of the row.
middle
Center the padding box of the cell within the row.
bottom
Align the bottom padding edge of the cell with the bottom of the row.
此外,您可能还想尝试其他一些技巧,例如将line-height
设置为等于父容器的高度。
答案 2 :(得分:0)
使用表格可以使用
<table>
<tr>
<td valign="middle"></td>
</tr>
</table>
或css
td{
vertical-align:middle;
}
如果你想要css垂直对齐是div的中间 使用display:table-cell;并显示:table;
#abc{
font:Verdana, Geneva, sans-serif;
font-size:18px;
text-align:left;
background-color:#0F0;
height:50px;
display: table;
width: 100%;
}
#abc span {
vertical-align:middle;
display: table-cell;
}
答案 3 :(得分:0)
这对您来说可能是一个惊喜,但是vertical-align
一直是一件令人困惑的事情,即使对于最小的divs
以下是了解它的一些很棒的资源:
你必须要了解的是何时使用这个属性,当不是=&gt;在某些情况下,它仅适用于table
s,而在某些情况下,您必须选择纯css
方法!
答案 4 :(得分:0)
我对模态居中的最爱是使用position
和translate
的组合,如下所述:http://css-tricks.com/centering-percentage-widthheight-elements/
总结:
.center {
width: 50%; /* or whatever you want your width to be; defaults to 100% */
height: 50%; /* or whatever you want your height to be; defaults to wrapping content */
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
-webkit-transform: translate(-50%, -50%);
-moz-transform: translate(-50%, -50%);
-o-transform: translate(-50%, -50%);
-ms-transform: translate(-50%, -50%);
}
根据您的使用情况,这可能会或可能不会起作用,但这是您工具箱中的一个好方法。