MoreThanChaos
MoreThanChaos

Reputation: 2092

SVG inside DIV displays incorrectly

I got as task to make some text that is covered with texture, SVG since it seems even to run good in IE8 seemed like good idea, but I have hard time positioning it inside div. SVG consist of few lines of text that should be centered in parent DIV but i have hard time getting it to work as I want. It seems I get confused somewhere half way between CSS ans SVG properties.

Here is what I've come up with already:

http://jsfiddle.net/HVTA4/

<div class="demo1">
<svg>
    <defs>
        <pattern id="diagonal" patternUnits="userSpaceOnUse" width="840" height="960">
            <image xlink:href="http://i.imgur.com/GWYrynq.jpg" width="840" height="960" />
        </pattern>
    </defs>
    <text x="0" y="0" style="text-anchor: middle;">
        <tspan x="0" dy="1.2em">1st line1st line</tspan>
        <tspan x="0" dy="1.2em">2nd line</tspan>
        <tspan x="0" dy="1.2em">3rd line</tspan>
        <tspan x="0" dy="2.8em">lastline</tspan>
    </text>
</svg>

body {
font: .9em Helvetica, Arial, sans-serif;
background: darkgreen;
margin: 0;
padding: 0;
color: #575142;
}
text {
    fill: url(#diagonal);
}
.demo1 {
    width:305px;
    height: 335px;
    display:block;
    background: #FFEE1F;
    font-size: 42px;
    text-align: center;        
    font-weight: bold;
    color: darkgreen;
    overflow:hidden;
    position:relative;
    top: 50px;
    left: 50px;
    margin: 0;
    padding: 0;
}

.demo1 svg {
    display:block;
    margin: 0;
    padding: 0;
}

Cheers mth

Upvotes: 1

Views: 239

Answers (2)

defghi1977
defghi1977

Reputation: 5349

Add svg element size and set text element's position to 50%.

.demo1 svg {
    display:block;
    margin: 0;
    padding: 0;
    width:100%;
    height:100%;
}
<text x="50%" y="0" style="text-anchor: middle;">
    <tspan x="50%" dy="1.2em">1st line1st line</tspan>
    <tspan x="50%" dy="1.2em">2nd line</tspan>
    <tspan x="50%" dy="1.2em">3rd line</tspan>
    <tspan x="50%" dy="2.8em">lastline</tspan>
</text>

Upvotes: 1

Adrift
Adrift

Reputation: 59799

For the first question, you can just set the x attribute of each <tspan> to 50%

<text x="0" y="0" text-anchor="middle">
    <tspan x="50%" dy="1.2em">1st line1st line</tspan>
    <tspan x="50%" dy="1.2em">2nd line</tspan>
    <tspan x="50%" dy="1.2em">3rd line</tspan>
    <tspan x="50%" dy="2.8em">lastline</tspan>
</text>

http://jsfiddle.net/HVTA4/2/

Upvotes: 1

Related Questions