user3719454
user3719454

Reputation: 1016

CSS: position absolute - how to set "left" property so it refers to the middle of the positioned element?

I drew a circle with svg (which is also positioned absolute) and I would like to put text into the middle of the circle. It's is no problem if the text is 1 character long, but the content of the page may change dynamically and the text width could be 2 or 3 characters long as well:

<div id="someDivWrap" style="position:relative">
    <svg id="someCircle" style="position:absolute;left:200px;right:300px">
        ...
    </svg>
    <span id="textInMidOfCirc" style="position:absolute;left:245px;right:341px">X</span>
</div>

But text in the middle of the circle could be X or XX or XXX.

EDIT:

here is the complete code:

<div id="someDivWrap" style="position:relative;width:174px;height:434px;border: 4px solid #525878;background-image: linear-gradient(#5bb8ff, #5f80e4); margin-left:255px">

    <svg id="someCircle" style="position:absolute;left:-120px;top:300px" width="120" height="240">
        <defs>
            <linearGradient id="CalenderGradient" x1="0" x2="0" y1="0" y2="1">
                <stop offset="0%" stop-color="#f8e498" />
                <stop offset="100%" stop-color="#d2811d" />
            </linearGradient>
        </defs>
        <circle cx="50" cy="50" r="40" stroke="black" stroke-width="0" fill="url(#CalenderGradient)" />
        <circle cx="50" cy="50" r="15" stroke="black" stroke-width="0" fill="black" />
    </svg>
    <span id="textInMidOfCirc" style="position:absolute; left:-75px; top:341px; color:lime; font-weight:bold">X</span>

</div>

Yes, and I need the circle as an SVG.

Upvotes: 0

Views: 76

Answers (1)

Dejan.S
Dejan.S

Reputation: 19158

If I get this right you want this.

There are more ways to do this but you can add width and height to the container and a display flex to position (center) the text. Position the SVG absolute and keep the text relative.

Keep in mind I added a background-colour and border radius to the container that you can remove, it's only there for demo purposes.

<div id="someDivWrap" style="position:relative; width: 300px; height: 300px; display: flex;
align-items: center; justify-content: center; background-color: aqua; border-radius: 50%;">
  <svg id="someCircle" style="position:absolute; top: 0;
    left: 0; width: 100%; height: 100%;">
    ...
  </svg>

  <span id="textInMidOfCirc">X</span>
</div>

Upvotes: 1

Related Questions