Rotating <text> relative to <rect> using SVG

I am in the process of creating a legend for my d3 project. I have ten rectangles arranged from left to right and I want to position text above each rectangle at a slight angle to the right. I have tried applying rotation but it seems to be rotating all the text elements as a group, instead of individually relative to each cell.

Does anyone have any suggestions on how to style or group the elements differently so that each text element rotates around its own center, rather than in a single line?

Below is the current state of my code:

    <svg preserveAspectRatio="xMinYMin meet" viewBox={`0 0 800 70`}>
      <g transform={`translate(${[dms.marginTop, dms.marginLeft].join(',')}`>
        <g>
          {range(10).map((d) => (
            <>
              <rect
                key={`${d}_legendCell`}
                width={cellSize - 1.5}
                height={cellSize - 1.5}
                fill={colorScale(Number(legendBands(String(d))) + interval)}
                x={d * cellSize}
              ></rect>
              <text
                key={`${d}_legendLabel`}
                fontWeight="300"
                fontSize="12"
                width="100"
                y={cellSize * d}
                transform="rotate(290)"
                dy=".85rem"
              >
                {Number(legendBands(String(d))).toFixed(1)}
              </text>
            </>
          ))}
        </g>
      </g>
    </svg>

Any help would be greatly appreciated!

Answer №1

After reviewing your code, it appears that your <text> elements are currently aligned vertically and rotated. I recommend using horizontal offsets instead for better alignment.

Alternatively, you can position your label elements with specific x coordinates relative to the center of your current rectangle.

Example 2nd cell

  <rect x="10" y="0" width="10" height="10" fill="magenta"/>
  <text x="15" y="5" width="10" dominant-baseline="central" text-anchor="middle" transform="rotate(-45, 15, 5)">02</text>

The value of x (15) in the text element represents the center point of the current cell/rectangle.

dominant-baseline="central"
and text-anchor="middle" simplify the horizontal and vertical alignment in relation to the preceding <rect>.
This x-value is then copied to the transformation:

transform="rotate(-45, 15, 5)"

This approach ensures that the label is rotated around the center of the rectangle.
Furthermore, this method proves to be quite reliable considering some browsers still encounter issues with transform-origin and transform-box (especially certain versions of Safari).

Static SVG Example

svg {
  display: block;
  border: 1px solid #ccc;
}

text {
  font-size: 5px
}
<svg width="50%" viewBox="0 0 30 10">
  <rect x="0" y="0" width="10" height="10" fill="green"/>
  <text x="5" y="5" width="10" dominant-baseline="central" text-anchor="middle" transform="rotate(-45, 5, 5)">01</text>
  
  <rect x="10" y="0" width="10" height="10" fill="magenta"/>
  <text x="15" y="5" width="10" dominant-baseline="central" text-anchor="middle" transform="rotate(-45, 15, 5)">02</text>
  
  <rect x="20" y="0" width="10" height="10" fill="cyan"/>
  <text x="25" y="5" width="10" dominant-baseline="central" text-anchor="middle" transform="rotate(-45, 25, 5)">03</text>
</svg>

<p>Add gaps</p>
<svg width="50%" viewBox="0 0 32 10">
  <rect x="0" y="0" width="10" height="10" fill="green"/>
  <text x="5" y="5" width="10" dominant-baseline="central" text-anchor="middle" transform="rotate(-45, 5, 5)">01</text>
  
  <rect x="11" y="0" width="10" height="10" fill="magenta"/>
  <text x="16" y="5" width="10" dominant-baseline="central" text-anchor="middle" transform="rotate(-45, 16, 5)">02</text>
  
  <rect x="22" y="0" width="10" height="10" fill="cyan"/>
  <text x="27" y="5" width="10" dominant-baseline="central" text-anchor="middle" transform="rotate(-45, 27, 5)">03</text>

</svg>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the proper method for incorporating text into d3.js nodes?

As I venture into the world of d3.js, I've decided to experiment with some sample code from this particular page and tweak it according to my needs. My main goal is to include TEXT within the colored nodes. Although these nodes already have a title p ...

Changing the background of a Muitextfield input element conceals the label

Struggling to customize the Textfield from the global theme? Can't seem to achieve a colored background for the input only (white) without obscuring the label when it moves inside the input. Desired result : https://i.sstatic.net/us2G7.png Current o ...

Transforming Angular Material Dialog component into a Bottom-sheet for mobile screens with the help of CSS

Is there a way to convert the positioning of a mat-dialog from center (on desktop) to bottom in full width (on mobile devices)? I want it to resemble a dialog on larger screens and a bottom-sheet on smaller devices. Currently, I have achieved this using th ...

The information presented in the following content seamlessly complements the captivating banner image

I am facing an issue with my banner image that is supposed to display only on small devices in a specified section. For more details, please refer to the following Stackoverflow Topic However, this setup has caused the content below to overlap and no long ...

Adjust the appearance of self and other classes on hover using CSS

I'm looking for a way to use the :hover effect in CSS to change the font color of one class (.footer_status_tex) and the background color of another class (.footer_status_gear). Here's a simplified version of what I have in mind: CSS .footer_s ...

Issue with responsive canvas height in Particle-JS

Recently, I've been working on a Bootstrap portfolio where I am experimenting with implementing particle.js over a profile picture. I placed the particles inside a DIV and set a background image as the profile photo. The issue arises when I reload th ...

<td> issue with IE not rendering overflow:hidden properly

In an effort to display text in a TD, I've implemented the overflow property set to hidden for the td element. Surprisingly, this code works flawlessly in Chrome, Safari, and Mozilla browsers, but unfortunately falls short in IE. Despite attempting to ...

Divergent Appearance of Input Field in Chrome versus Firefox

After testing in Chrome and Firefox, I noticed that the input box appears larger than expected in Firefox. Below is the HTML markup: <div class="form-wrapper"> <input type="search" name="Ofsearch" placeholder="Search h ...

Create a div in CSS that is square and relatively positioned

Is there a way to use CSS alone to ensure that a div with relative positioning remains perfectly square in all scenarios? I have a script that allows users to upload images, which are then applied as the background image. The challenge is that the system ...

Tips for maintaining the button color when clicking and refreshing the page

By default, the color of my like button is gray. When a user clicks the like button, it will trigger the togglepost "like" function and the color will change to red. I am using AJAX to insert the data when the like button is clicked. If the user clicks the ...

Guide on incorporating Bootstrap JS into HTML5 reusable web elements

RESOLVED: the solution is in a comment TL;DR: Issues triggering Bootstrap's JS, likely due to incorrect import of JS scripts I've been working on integrating Bootstrap with my custom reusable web components across all pages. Specifically, I&apo ...

Restricting CSS Background Image Width to 960 Pixels

My CSS style is causing my background image to span across the whole screen instead of repeating within the 960px width of the body. body { width:960px; margin: 10px auto 10px auto; background-image:url(logo.png),url(backgroundimage.jpg); ...

What is the correct way to utilize Bootstrap grid offsets?

Recently, I have been working on a webpage that features a unique layout using Bootstrap grid rows. Each row consists of a paragraph of text and an image. The layout is designed to have the text occupy specific columns on large screens, with the image shif ...

Issue with LESS CSS: Inability to divide two pixel units and provide a value without units

I want to temporarily strip the units from my variables @baseLineHeight and @baseFontSize so that I can divide them to get a relative line-height. Here is my attempt: @baseFontSize: 12px; @baseLineHeight: 18px; font: @baseFontSize~"/"@baseLineHeight/@baseF ...

Moving the search bar on a WordPress mobile theme: A step-by-step guide

As a novice in web design, I've taken on the task of self-hosting a Wordpress site at noisehole.com using the MH Magazine template. One modification I made was to include a search bar above the header by creating a child theme and customizing it. How ...

"Implementing a consistent body border design on all pages using CSS for print media

Having an issue with my html page layout where I am unable to display a border on both printable pages. My current code only adds the border to the first page. Any suggestions on what I need to change in order to show the border on every printed page? Be ...

What is the best way to incorporate a minimum width and maximum width in CSS that add up to 100% when necessary?

Can anyone help me find CSS rules that can set a fixed width for an element (width: 500px) but also allow it to be responsive with max-width: 100% if the container is narrower than the element? I saw this example and it works perfectly: .elem { width: 60 ...

I am keen on eliminating the lower margin of the PIXI application

Exploring the possibilities of PIXI.js, I am working on creating a new application. However, upon adding the PIXI application to the DOM, I noticed an unwanted margin at the bottom. Here is an image illustrating the issue. Is there a way to remove this bo ...

Modify the colors of multiple texts using a concise code block of fewer than 20 lines

I have 8 paragraphs and I want to toggle the class 'one-active' when clicking on each of them, while removing the active class from the others. I currently have the code working for two paragraphs, but it's too lengthy for all eight. How can ...

How can you position an absolute DIV with an unknown height outside of a "relative" parent using CSS?

Imagine a straightforward illustration using html: <div class="parent"> <div class="child"> </div> </div> and CSS: .parent{ position:relative; background:red; width:200px; height:40px; } .child{ positi ...