Brad Woods
Brad Woods

Reputation: 1546

appending svg and stretching to parent

In the example below I have 3 divs:

The questions I have are;

  1. Why is the 2nd SVG pushed down the page? I simply put an SVG within a div, no margins were altered.
  2. By default, an SVG width and height are 100%, therefore if you put an SVG into a container it should stretch to fill that container. However when I append an SVG through JS it doesn't.

http://codepen.io/BradLee/pen/oxvQMN?editors=1010

<div></div>

<div>
    <svg viewbox="0 0 24 24">
        <path d="M2,14l6,6h12c1.1,0,2-0.9,2-2V6c0-1.1-0.9-2-2-2L4,4C2.9,4,2,4.9,2,6V14z M9,18.5L3.5,13H9V18.5z"/>
        <path fill="none" d="M0,0h24v24H0V0z"/>
    </svg>
</div>

<div class="svgAppendDiv"></div>


div{
    display: inline-block;
    margin-left: 100px;
    background-color: tomato;
    width: 300px;
    height: 300px;
}


var myDiv = document.querySelector(`.svgAppendDiv`);

function createElement () {
    let svg = document.createElementNS("http://www.w3.org/2000/svg", 'svg');
    svg.setAttribute(`xmlns`, `http://www.w3.org/2000/svg`);
    svg.setAttribute(`viewbox`, `0 0 24 24`);
    svg.setAttribute(`preserveAspectRatio`, `none`);

    let path = document.createElementNS("http://www.w3.org/2000/svg","path");
    path.setAttribute("d", "M2,14l6,6h12c1.1,0,2-0.9,2-2V6c0-1.1-0.9-2-2-2L4,4C2.9,4,2,4.9,2,6V14z M9,18.5L3.5,13H9V18.5z");

    svg.appendChild(path);
    myDiv.appendChild(svg);
};

createElement();

Upvotes: 0

Views: 274

Answers (1)

Paul LeBeau
Paul LeBeau

Reputation: 101820

Why is the 2nd SVG pushed down the page?

It's caused due to an interaction between your CSS and one of the stylesheets you are including (material.blue-amber.min.css)

You are redefining <div> to be inline-block, and the stylesheet is setting <svg> to have vertical-align: middle.

To override that, add the following rule to your CSS to reset the alignment.

svg {
    vertical-align: baseline;
}

By default, an SVG width and height are 100%, therefore if you put an SVG into a container it should stretch to fill that container. However when I append an SVG through JS it doesn't.

You spelled viewBox incorrectly. Attributes in SVG are case sensitive. If you fix that, it'll work.

Updated codepen: http://codepen.io/anon/pen/NNjRva

Also as an aside

  1. You are using a back-tick instead of a single quote in some of your JS. That'll work in recent browser versions. But you may want to avoid making a habit of it, if you are writing code that needs to work in older browsers.

  2. You don't need to set the xmlns attribute explicitly like you are doing. It is done for you when you use createElementNS().

Upvotes: 1

Related Questions