Jimmy
Jimmy

Reputation: 12487

Position SVG item relative to text

This is my code:

<?xml version="1.0">
  <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" 
  "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
  <svg width="100%" height="100%" viewBox="0 0 100 30" version="1.1">
  <text id="t1" x="50%" y="50%" text-anchor="middle">Hello World</text>
  <g transform="translate(0,0) rotate(0)">
    <rect x="0" y="0" width="10" height="10" fill="blue" />
    </g>
  </svg>

This gives me hello world and a rectangle. I would like to know how to position my rectangle relative to my text. I thought this would do the trick, but according to my code above the rectangle should sit on top of the text but it does not.

Edit: I tried this but it didn't change anything:

<?xml version="1.0">
  <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" 
  "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
  <svg width="100%" height="100%" viewBox="0 0 100 30" version="1.1">
    <g transform="translate(0,0) rotate(0)">
    <rect x="0" y="0" width="10" height="10" fill="blue" />
    </g>
<text id="t1" x="50%" y="50%" text-anchor="middle">Hello World</text>

  </svg>

Upvotes: 0

Views: 298

Answers (2)

Momin
Momin

Reputation: 3320

Another Approach you can try! Maybe It will fit for you ...

p {
  font-size: 42px;
}

p>svg {
  width: 60px;
  height: 60px;
  display: inline-block;
  position: relative;
  top: 28px;
}
<div style="display:none">
  <svg width="100%" height="100%" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
    <symbol viewBox="0 0 20 20" id="box">
      <g transform="translate(0,0) rotate(0)">
        <rect x="0" y="0" width="12" height="12" fill="blue" />
      </g>
    </symbol>
  </svg>
</div>
<p>
  <svg>
    <use xlink:href="#box"></use>
  </svg> Hello World
</p>

Upvotes: 0

Paul LeBeau
Paul LeBeau

Reputation: 101800

Is this close to what you want?

<svg width="100%" height="100%" viewBox="0 0 100 30" version="1.1">
  <rect x="0" y="0" width="100%" height="100%" fill="blue" />
  <text id="t1" x="50%" y="50%" text-anchor="middle" dy="0.3em">Hello World</text>
</svg>

The correct value to use for dy, to get the text vertically centred, is font specific. You may have to tweak that value to match whichever font you choose. In my opinion, it is a more reliable alternative to other solutions like alignment-baseline etc.

Upvotes: 2

Related Questions