Html CSS 中 SVG 的垂直对齐
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35962438/
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
Vertical Alignment of SVG in CSS
提问by MyWetSocks
I have a problem with inline SVG alignment. I have created a button with some text and an SVG. And while the alignment works correctly when the SVG is at least as big as the text it fails when the SVG height is smaller than the text.
我有内联 SVG 对齐问题。我创建了一个带有一些文本和 SVG 的按钮。虽然当 SVG 至少与文本一样大时对齐工作正常,但当 SVG 高度小于文本时它会失败。
I have created a test case with a two-colored background button to indicate where exactly the middle is. You can see if you look closer that the second case is not perfectly aligned because the height of the SVG is less than the one from the text.
我创建了一个带有两种颜色背景按钮的测试用例,以指示中间的确切位置。如果仔细观察,您会发现第二种情况没有完全对齐,因为 SVG 的高度小于文本的高度。
Is there any way to fix this? Doing it some other way (no js please)?
有没有什么办法解决这一问题?以其他方式做(请不要js)?
Test case: https://goo.gl/KYDKGH
测试用例:https: //goo.gl/KYDKGH
回答by Le____
jsfiddle 1- You can use position:relative
on the container and position:absolute
on the objects like this:
jsfiddle 1- 您可以position:relative
在容器和position:absolute
这样的对象上使用:
position: absolute;
top: 50%;
-webkit-transform: translateY(-50%);
-ms-transform: translateY(-50%);
transform: translateY(-50%);
left: 0;
right: 0;
margin: auto;
text-align: center;
The top: 50%
moves the object to the container's vertical center picking the top of the object as reference (not its center), so the transform: translateY
moves it a distance of 50% of it's size upwards to let it exactly on the middle of the container (by the objects center).
该top: 50%
拾取对象作为参考(而不是它的中心)的顶部将对象移动到所述容器的垂直中心,因此transform: translateY
移动时,它的它的大小的50%的距离向上让它恰好在所述容器的中间(由对象中央)。
ps: the text-align:center;
left:0;
right:0;
and margin:auto
are for horizontal align.
ps:text-align:center;
left:0;
right:0;
和margin:auto
用于水平对齐。
jsfiddle 2- Or use display:flex
on the container with align-items
to vertical align the content like this:
jsfiddle 2- 或者display:flex
在容器上使用align-items
垂直对齐内容,如下所示:
display: -webkit-flex; /* Safari */
display: flex;
-webkit-align-items: center; /* Safari 7.0+ */
align-items: center;
-webkit-justify-content: center;
justify-content: center;
ps: the justify content
is for horizontal align.
ps:justify content
用于水平对齐。