Alan De Smet
Alan De Smet

Reputation: 1770

How to place HTML elements over inline SVG

I'm able to use z-index to put various HTML elements over each other in whatever order I like, except when one of the elements in an inline SVG. For example, given the HTML

<div>
    <p>Text before SVG. I'm some boring text. Such incredibly boring text. Who would possibly want to read such boring text?</p>
    <svg version="1.1" baseProfile="full" width="200" height="200" xmlns="http://www.w3.org/2000/svg">
        <circle cx="75" cy="40" r="20" fill="red" />
    </svg>
</div>
<div>
    <svg version="1.1" baseProfile="full" width="200" height="200" xmlns="http://www.w3.org/2000/svg">
        <circle cx="75" cy="75" r="20" fill="red" />
    </svg>
    <p>SVG before text. I'm some boring text. Such incredibly boring text. Who would possibly want to read such boring text?</p>
</div>

and the matching CSS

p {
    width: 200px;
    z-index:10;
}
div {
    position: relative;
}
svg {
    position: absolute;
    left: 0;
    top: 0;
    z-index: 1;
}

no matter how I order the two or adjust the z-index, the inline SVG renders on top of the text. How can I get the SVG behind the text?

The example above is available at https://jsfiddle.net/o0n10j78/1/ .

If it's relevant, in my actual application I'm generating nearly all of the document structure in Javascript with the assistance of jQuery, including the inline SVG and the HTML block I wish to have in front of it.

Upvotes: 30

Views: 65760

Answers (3)

Hugo Bayoud
Hugo Bayoud

Reputation: 233

Adding z-index: -1 as suggest by Fazil Abdulkhadar didn't work for me because I have a background. Therefore, my svg will be behind my background.

As suggest by Hoshts, I put position: relative; on the elements I want in front of my absolute svg.

For the example of this issue, it will be :

p {
   position: relative; // add it
   width: 200px;
   /* z-index: 10; */ // change it to z-index: 1;
}
div {
   position: relative; // not sure it is necessary
}
svg {
   position: absolute;
   left: 0;
   top: 0;
   /* z-index: 1; */ // remove it
}

Upvotes: 3

user1583190
user1583190

Reputation:

The z-index property is only being applied on positioned elements. Adding position: relative; to the paragraph tag will correctly apply it.

Look at this page for a full reference of the property.

On a side note: As I first wrote in a comment, setting the svg z-index to -1 works as it lowers the priority of the element below the default that all elements have. This comes with the downside that the svg actually being placed behind the div as well. Try apply a background color to the div while having the svg z-index set to -1.

Upvotes: 57

Fazil Abdulkhadar
Fazil Abdulkhadar

Reputation: 1101

Please add a z-index:-1 to the svg.

svg {
    position: absolute;
    left: 0;
    top: 0;
    z-index: -1;
}

Upvotes: 18

Related Questions