简体   繁体   English

CSS 垂直 alignment 的内联/内联块元素

[英]CSS vertical alignment of inline/inline-block elements

I'm trying to get several inline and inline-block components aligned vertically in a div .我试图让几个inlineinline-block组件在div中垂直对齐。 How come the span in this example insists on being pushed down?这个例子中的span怎么坚持要往下推呢? I've tried both vertical-align:middle;我已经尝试了两个vertical-align:middle; and vertical-align:top;vertical-align:top; , but nothing changes. ,但没有任何变化。

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:结果:
在此处输入图像描述

FIDDLE小提琴

vertical-align applies to the elements being aligned, not their parent element. vertical-align适用于被对齐的元素,而不是它们的父元素。 To vertically align the div's children, do this instead:要垂直对齐 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-align is relative to the current text line, not the full height of the parent div .注意vertical-align是相对于当前文本行,而不是父div的全高。 If you wanted the parent div to be taller and still have the elements vertically centered, set the div 's line-height property instead of its height .如果您希望父div更高并且仍然具有垂直居中的元素,请设置divline-height属性而不是它的height Follow jsfiddle link above for an example.上面的jsfiddle链接为例。

Give vertical-align:top;vertical-align:top; in a & span .aspan Like this:像这样:

a, span{
 vertical-align:top;
}

Check this http://jsfiddle.net/TFPx8/10/检查这个http://jsfiddle.net/TFPx8/10/

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;
}

For fine tuning the position of an inline-block item, use top and left:要微调inline-block项目的位置,请使用 top 和 left:

  position: relative;
  top: 5px;
  left: 5px;

Thanks CSS-Tricks !感谢CSS 技巧

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM