Can I display an SVG image as a div background wit

2019-07-08 02:29发布

In an HTML page, I want to use an SVG image as a background in a div element, with a pre element with text on top of of it (the background). The background image should scale with the containing div, while maintaining aspect ratio.

Can I accomplish this task with one of the SVG JavaScript libraries, such as jQuery SVG / Raphaël / svgweb?

The kind of structure I'd like to add a background image to:

<div>
  <pre>Some text...</pre>
</div>

3条回答
Root(大扎)
2楼-- · 2019-07-08 02:42

You could always cheat and use position: absolute to put two divs in the same place.

查看更多
相关推荐>>
3楼-- · 2019-07-08 02:47

You can use an SVG image as a CSS background, providing you only want to support recent browsers, use background-size to scale the image and maintain the aspect ratio. Here the image is applied directly to the pre, just to demonstrate:

pre {
    outline: 2px dashed black;
    padding: 1em;
    background-image: url(http://upload.wikimedia.org/wikipedia/commons/8/84/Konqi_svg.svg);
    background-repeat: no-repeat;
    background-size: cover;
}

If you want to support IE8 and FF3.6 then you'll have to resort to absolutely positioned elements as andrewmu suggests.

查看更多
Deceive 欺骗
4楼-- · 2019-07-08 03:02

SVG images are part of the DOM they cannot be a div background, instead they are an element just like a div.

You could place an SVG image behind a transparent div to get the illusion of a background. This just involves positing your SVG and content in the proper place.

to get scaling you should use some math to maintain aspect ratio, should be pretty easy, the word ratio is involved. That would be a clue on how to do that.

EDIT

It looks like I was wrong http://www.broken-links.com/2010/06/08/using-svg-in-background-image/ it can be a background.

查看更多
登录 后发表回答