2

I'm trying to center an svg path element to the center of an svg element responsively?

I have tried translate(Xpx, Ypx) but that breaks over different screen resolutions.

This is my setup,

CSS:

#sky{
   width: 100%;
   height: 200px;
   background-color: skyblue;
}
        
#container{
   display: block;
   margin: 0 auto;
}

HTML:

<svg id="sky">
  <g id="container">
    <path id="cloud" fill="#ffffff" d="M64.407,24.849c-0.013,0-0.026,0.002-0.04,0.002c0.019-0.261,0.04-0.522,0.04-0.788c0-5.944-4.819-10.764-10.763-10.764c-2.383,0-4.577,0.784-6.361,2.094c-2.624-5.62-8.31-9.524-14.922-9.524c-9.1,0-16.477,7.377-16.477,16.477c0,0.896,0.091,1.769,0.229,2.627C10.485,25.758,6.15,30.577,6.15,36.42c0,6.391,5.181,11.572,11.572,11.572h46.685c6.392,0,11.572-5.181,11.572-11.572C75.979,30.029,70.798,24.849,64.407,24.849z"></path>
  </g>
</svg>

see the JsFiddle

I want a way which works over different resolutions, like % with divs.

thanks.

Community
  • 1
  • 1
All Іѕ Vаиітy
  • 24,861
  • 16
  • 87
  • 111

1 Answers1

1

So I wouldn't normally use jQuery for styling, but I believe this is an exception because it will not budge with any CSS that I've tried. Here is a little function I wrote to center the cloud, even if you resize the page.

jQuery:

function centerCloud() {
  var cloudCenter = $('#sky').outerWidth()/2 - 35;
  $('#cloud').css('transform', 'translate(' + cloudCenter + 'px, 0px)');
}

centerCloud();

$(window).on('resize', function(){
    centerCloud();
});

Here is a working fiddle.

Hunter Turner
  • 6,804
  • 11
  • 41
  • 56