Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Position SVG elements over an image

Tags:

html

css

svg

Is it possible to have the following elements and style them so that the SVG objects appear over the image (i.e. like part of the image)?

Currently they are displayed below it on a new row.

I know I could set the image as a background image of the parent div, but unfortunately I also need to be able to rotate it within the parent so I don't think that is an option.

<div id='edit-area' style='position:relative; overflow:none; display:inline-block; border: 1px black solid; width: 950px; height: 500px;'>
    <img src='/my_image.png' />
    <svg id="edit-svg" height="500" width="950">
        <!-- there will be lines, rectangles etc in here -->
    </svg>
</div>
like image 320
CompanyDroneFromSector7G Avatar asked May 05 '17 13:05

CompanyDroneFromSector7G


People also ask

What is SVG overlay?

Using absolute positioning in CSS, two external SVG images can be placed such that one overlays the other within an HTML document. It can also be positioned over or under HTML elements. HTML text.

How do I change position in SVG?

As mentioned in the other comment, the transform attribute on the g element is what you want. Use transform="translate(x,y)" to move the g around and things within the g will move in relation to the g .

How do I get SVG coordinates?

The element. getBoundingClientRect() method will return the proper coordinates of an element relative to the viewport regardless of whether the svg has been scaled and/or translated.

Can you nest svgs?

The SVG format allows for the nesting of SVG graphics. It is possible for an “<svg>” elements, to be placed within another “<svg>” element.


1 Answers

Here's a generic example of how to do an image overlay. Basically you wrap the image and the overlay content in a relative positioned element and then absolute position the overlay content.

.img-overlay-wrap {
  position: relative;
  display: inline-block; /* <= shrinks container to image size */
  transition: transform 150ms ease-in-out;
}

.img-overlay-wrap img { /* <= optional, for responsiveness */
   display: block;
   max-width: 100%;
   height: auto;
}

.img-overlay-wrap svg {
  position: absolute;
  top: 0;
  left: 0;
}

.img-overlay-wrap:hover {
  transform: rotate( 15deg );
}
<div class="img-overlay-wrap">

  <img src="https://via.placeholder.com/400">
  <svg viewBox="0 0 200 200">
    <circle cx="75" cy="75" r="50" fill="rebeccapurple"/>
  </svg>

</div>

Added a bit-o rotation fun since you mentioned rotation (might be different than what you intended).

like image 62
hungerstar Avatar answered Sep 20 '22 05:09

hungerstar