Vertical alignment of SVG in CSS

I have a problem with SVG alignment. I created a button with text and SVG. And while alignment works correctly when the SVG is at least as large as the text, it fails when the height of the SVG is less than the text.

I created a test case with a two-color background button to indicate exactly where the middle is. You can see if you look closer so that the second case is not completely aligned because the height of the SVG is less than the height of the text.

Is there any way to fix this? Doing it differently (no js please)?

Test case: https://goo.gl/KYDKGH

+5
source share
1 answer

jsfiddle 1 - you can use position:relative in the container and position:absolute on objects like this:

  position: absolute; top: 50%; -webkit-transform: translateY(-50%); -ms-transform: translateY(-50%); transform: translateY(-50%); left: 0; right: 0; margin: auto; text-align: center; 

top: 50% moves the object to the vertical center of the container, which selects the top of the object as a link (rather than its center), so transform: translateY moves it up to 50% of its size up so that it exactly matches the middle of the container (the center of the objects).

ps: text-align:center; left:0; right:0; and margin:auto are for horizontal alignment.

jsfiddle 2 - Or use display:flex in a container with align-items to vertically align content for example:

  display: -webkit-flex; /* Safari */ display: flex; -webkit-align-items: center; /* Safari 7.0+ */ align-items: center; -webkit-justify-content: center; justify-content: center; 

ps: justify content is for horizontal alignment.

+15
source

Source: https://habr.com/ru/post/1244944/


All Articles