Home > Net >  Is it possible to center align <rect>'s inside a <g> for SVG?
Is it possible to center align <rect>'s inside a <g> for SVG?

Time:06-03

Is it possible to vertically center align all the rects inside a tag without having to adjust the y attributes on <rect>? (see snippet for example)

<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3/org/1999/xlink" viewBox="0 0 225 38" preserveAspectRatio="none" width="100%" height="100%">
  <g fill="black">
    <rect x="10" y="1" width="6" height="5" />
    <rect x="20" y="1" width="6" height="10" />
    <rect x="30" y="1" width="6" height="20" />
    <rect x="40" y="1" width="6" height="5" />
    <rect x="50" y="1" width="6" height="15" />
  </g>
</svg>

<h3>desired result</h3>
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3/org/1999/xlink" viewBox="0 0 225 38" preserveAspectRatio="none" width="100%" height="100%">
  <g fill="black">
    <rect x="10" y="8" width="6" height="5" />
    <rect x="20" y="6" width="6" height="10" />
    <rect x="30" y="1" width="6" height="20" />
    <rect x="40" y="8" width="6" height="5" />
    <rect x="50" y="4" width="6" height="15" />
  </g>
</svg>

CodePudding user response:

No, it's not possible to center align <rect> elements.

But it is possible to center-align <line> elements and give them a stroke-width (note the viewBox is vertically centered around 0):

<svg viewBox="0 -19 225 38" width="100%" height="100%">
  <g stroke="black">
    <line x1="10" x2="16" stroke-width="5" />
    <line x1="20" x2="26" stroke-width="10" />
    <line x1="30" x2="36" stroke-width="20" />
    <line x1="40" x2="46" stroke-width="5" />
    <line x1="50" x2="56" stroke-width="15" />
  </g>
</svg>

CodePudding user response:

You could also achieve vertically centered <rect> elements by setting a transform: translate(0, -50%) css rule.

This approach also requires a transform-box: fill-box; (or content-box) property.

All <rect>elements get a y="50%" attribute to start at the vertical center of the svg viewBox.

<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3/org/1999/xlink" viewBox="0 0 225 38"  width="100%" height="100%" style="border:1px solid #ccc">
  <style>
    rect {
      transform: translate(0, -50%);
      transform-origin: center;
      transform-box: fill-box;
    }
  </style>
  <g fill="black" >
    <rect x="10" y="50%" width="6" height="5" />
    <rect x="20" y="50%" width="6" height="10" />
    <rect x="30" y="50%" width="6" height="20" />
    <rect x="40" y="50%" width="6" height="5" />
    <rect x="50" y="50%" width="6" height="15" />
  </g>
</svg>

Browser support for transform-box is decent. (See caniuse).
However, if you need legacy browser (e.g. ie11) support, @ccprog's answer is a more robust solution.

  •  Tags:  
  • svg
  • Related