CSS 如何将一个元素定位在另一个元素的中间(高度的一半/垂直 50%)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14940540/
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 how to position an element in a middle (half height / vertical 50%) of another element
提问by elon
I'm looking forward to build a tooltip which is positioned next to the element. It's easy to put it over and under in the center of element. But is there a way to do so vertically (on the right or left side of an element, vertically positioned in a middle of that element height)?
我期待构建一个位于元素旁边的工具提示。很容易将它放在元素的中心上下。但是有没有办法垂直这样做(在元素的右侧或左侧,垂直放置在该元素高度的中间)?
For my purpose, height of the element is known & height of tooltip is not. And tooltip can be a child of element.
就我而言,元素的高度是已知的,而工具提示的高度则不是。工具提示可以是元素的子元素。
However, I'm also curious about how to do it when both heights are unknown. By heights I understand element's and tooltip's height. Width can be known and fixed.
但是,我也很好奇在两个高度都未知的情况下如何做到这一点。通过高度,我了解元素和工具提示的高度。宽度可以已知并固定。
回答by trgraglia
This is pretty late but I tried to make an example on codepen which shows a working example if I understood your question correctly.
这已经很晚了,但我试图在 codepen 上做一个例子,如果我正确理解了你的问题,它会显示一个有效的例子。
http://codepen.io/trgraglia/pen/RWbKyj
http://codepen.io/trgraglia/pen/RWbKyj
Use CSS transform.
使用 CSS 转换。
For example, transform:translateX(-50%);
, will move an element left by 50% of ITSELF. Now you can align it to the parent with position
and bottom
or top
or left
or right
and then move it by the dimensions of itself.
例如,transform:translateX(-50%);
, 会将元素向左移动其自身的 50%。现在,你可以用它对准父position
和bottom
或top
或left
或right
然后通过自身的尺寸移动它。
Hope this helps!
希望这可以帮助!
回答by ggdx
using CSS & jQuery-
使用 CSS 和 jQuery-
CSS
CSS
.div{
top:50%
}
jQuery
jQuery
var divheight = $(.div).height() / 2;
$(.div).attr('style','margin-top:-'+divheight+'px;');
回答by Aljullu
If you don't know both heights, there are only two ways:
如果你不知道这两个高度,只有两种方法:
- Set the parent
display: table
and childrendisplay: table-cell
andvertical-align: middle
. - Using CSS3 Flexbox: http://www.w3.org/TR/css3-flexbox/but with limited browser support: http://caniuse.com/#search=flexbox
- 设置父级
display: table
和子级display: table-cell
和vertical-align: middle
. - 使用 CSS3 Flexbox:http: //www.w3.org/TR/css3-flexbox/但浏览器支持有限:http: //caniuse.com/#search=flexbox
If you are interested in this topic, here there is a good article with more tips: http://www.vanseodesign.com/css/vertical-centering/
如果您对此主题感兴趣,这里有一篇很好的文章,其中包含更多提示:http: //www.vanseodesign.com/css/vertical-centering/
As you can see, the only way to vertical align an element without knowing its height and nor using CSS3 is using display: table-cell
.
如您所见,在不知道元素高度且不使用 CSS3 的情况下垂直对齐元素的唯一方法是使用display: table-cell
.