CSS how to position element in half height (vertic

2019-03-26 07:35发布

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 element vertically positioned in a middle of elements height)?

For my purpose, height of the element is known & height of tooltip is not. And tooltip can be a child of element.

But, 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.

4条回答
女痞
2楼-- · 2019-03-26 07:57

If you don't know both heights, there are only two ways:

  1. Set the parent display: table and children display: table-cell and vertical-align: middle.
  2. Using CSS3 Flexbox: http://www.w3.org/TR/css3-flexbox/ but with limited browser support: 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/

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.

查看更多
神经病院院长
3楼-- · 2019-03-26 08:03

This is pretty late but I tried to make an example on codepen which shows a working example if I understood your question correctly.

http://codepen.io/trgraglia/pen/RWbKyj

Use CSS transform.

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.

Hope this helps!

查看更多
Fickle 薄情
4楼-- · 2019-03-26 08:03

using CSS & jQuery-

CSS

.div{
    top:50%
}

jQuery

var divheight = $(.div).height() / 2;
$(.div).attr('style','margin-top:-'+divheight+'px;');
查看更多
forever°为你锁心
5楼-- · 2019-03-26 08:17

If you know the height of the content the easiest way to center the tooltip is to set the line-height of tooltip to the height of content.You can see how i did that here jsFiddle

查看更多
登录 后发表回答