Html 内联/内联块元素的 CSS 垂直对齐
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9670469/
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
CSS vertical alignment of inline/inline-block elements
提问by Yarin
I'm trying to get several inlineand inline-blockcomponents aligned vertically in a div. How come the spanin this example insists on being pushed down? I've tried both vertical-align:middle;and vertical-align:top;, but nothing changes.
我试图让几个inline和inline-block组件的垂直对齐div。为什么span这个例子中的 坚持被推下?我已经尝试了vertical-align:middle;和vertical-align:top;,但没有任何改变。
HTML:
HTML:
<div>
<a></a><a></a>
<span>Some text</span>
</div>?
CSS:
CSS:
a {
background-color:#FFF;
width:20px;
height:20px;
display:inline-block;
border:solid black 1px;
}
div {
background:yellow;
vertical-align:middle;
}
span {
background:red;
}
?
RESULT:
?
结果:
回答by Diego
vertical-alignapplies to the elements being aligned, not their parent element. To vertically align the div's children, do this instead:
vertical-align适用于对齐的元素,而不是它们的父元素。要垂直对齐 div 的子项,请执行以下操作:
div > * {
vertical-align:middle; // Align children to middle of line
}
See: http://jsfiddle.net/dfmx123/TFPx8/1186/
见:http: //jsfiddle.net/dfmx123/TFPx8/1186/
NOTE: vertical-alignis relative to the current text line, not the full height of the parent div. If you wanted the parent divto be taller and still have the elements vertically centered, set the div's line-heightproperty instead of its height. Follow jsfiddlelink above for an example.
注意:vertical-align相对于当前文本行,而不是父级的全高div。如果您希望父div元素更高并且仍然让元素垂直居中,请设置div'sline-height属性而不是它的height. 遵循的jsfiddle为例上面的链接。
回答by sandeep
Give vertical-align:top;in a& span. Like this:
给vertical-align:top;中a和span。像这样:
a, span{
vertical-align:top;
}
Check this http://jsfiddle.net/TFPx8/10/
回答by HoldTheLine
Simply floating both elements left achieves the same result.
简单地向左浮动两个元素可以获得相同的结果。
div {
background:yellow;
vertical-align:middle;
margin:10px;
}
a {
background-color:#FFF;
width:20px;
height:20px;
display:inline-block;
border:solid black 1px;
float:left;
}
span {
background:red;
display:inline-block;
float:left;
}
回答by kslstn
For fine tuning the position of an inline-blockitem, use top and left:
要微调项目的位置inline-block,请使用 top 和 left:
position: relative;
top: 5px;
left: 5px;
Thanks CSS-Tricks!
感谢CSS 技巧!

