The width property is ineffective when used in conjunction with the d3 styling method

My goal is to create bar graphs where the width of each bar represents a person's age. However, I am having trouble applying the width attribute to the bars using the style method in d3 (I checked this by inspecting the elements in the browser). Other attributes that are applied using style seem to be working fine.

 function showData(clients){
        let max = d3.max(clients, (d) => {
            return (parseInt(d.age));
        })
        //console.log(max);

        let scale = d3.scaleLinear().domain([0, parseInt(max)]).range([0, 100]);
        //console.log(scale);

        let join = container.selectAll('div').data(clients);

        join.enter().append('div')
            .text((d) => {
                return d.name + ' : ' + scale(parseInt(d.age));
            })
            .style('background-color', 'blue')
            .style('margin', '5px')
            .style('color', 'white')
            .style('width', (d) => {
                return parseInt(d.age)
            });
    }

Answer №1

CSS width can be specified in various ways, not just as a simple number:

width: 150px;
width: 20em;
width: 75%;
width: auto;

In this case, it seems like you may want to use the following code:

.style('width', (data) => {
  return parseInt(data.age) + 'px';
});

Answer №2

When applying width or height to svg elements, it is recommended to use the .attr() method instead of .style(). Using numbers without specifying a unit like px will work in this case. If no unit is specified, it will default to pixels. Remember that when using width and height in the style attribute, you must always specify a unit regardless of the element being styled.

const width = 400,
  height = 200;
  
const svg = d3.select("svg")
  .attr("width", width)
  .attr("height", height)
  .style("background", "steelblue")
  .append("rect")
  .attr("width", 100)
  .attr("height", 200)
  .attr("fill", "tomato");
<script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="9bffa8dbadb5a8b5aa">[email protected]</a>/dist/d3.min.js"></script>
<svg></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

Achieving perfect alignment both horizontally and vertically using CSS3's viewport height of 100%

I'm trying to utilize CSS3's Viewport Height to create a fullscreen section with a height of 100vh. However, I am encountering difficulties in centering elements both horizontally and vertically within the section. My goal is to have an image and ...

Dropdown menu featuring a customizable input field

Is it possible to have a drop-down list with an input textbox field for creating new items in the same dropdown menu? ...

Gap created between two td or tr elements

Can someone please help me solve a troubling issue I'm facing with my CSS and HTML code? body { background-color:#ffffff; margin:0; padding-top:0px; } table.main-table-default { margin:0 auto; background-color:#00ffff; width:700px; border-collapse:co ...

Transforming a Bootstrap 4 dropdown navbar by replacing the caret with Fontawesome 5 icons for Plus and Minus

After spending several days trying to find a solution, I am still struggling. I have managed to create a responsive Navbar with Dropdowns using Bootstrap 4. Now, my goal is to replace the caret with a Plus and Minus sign at the end of each row on small dev ...

What is the best way to align HTML inputs within a grid, whether it be done automatically or manually using JavaScript?

Arrange 20 HTML inputs with various data types into grid-columns as the user inputs data. Ensure that the grid container has div elements correctly positioned for output. ...

What could be causing my website to have a horizontal scroll even when the width is set to 100%?

My website seems to be scrolling horizontally, possibly due to an issue with the footer. I suspect it might be related to the social media icons in the footer, but I'm not entirely sure. Any guidance on resolving this problem would be greatly apprecia ...

Stopping autoplay in Swiper as soon as you hover over it

My swiper is set to autoplay, but I want it to stop immediately when hovered over instead of waiting for the transition to finish. Is there a way to interrupt the transition and stop it at the exact point where the cursor hovers? Here is my Swiper config ...

How to Align the Button Vertically with the TextField in React Material-UI

Utilizing the Material-UI library for React, I have been working on creating a simple form with the following design: https://i.stack.imgur.com/LY3ZN.png My challenge lies in aligning the button with the TextField element. Adjusting the margin-top proper ...

What is the best way to create a full-width gallery display?

I've been having some trouble making my image gallery full-width at any resolution. Oddly enough, the gallery only goes full screen when I click on the maximize button in the browser window. I can't seem to figure out what the issue is so far. ...

Adjusting the Size of a Slideshow: HTML Tutorial

I'm currently working on a project to develop an interactive website using PHP and HTML for educational purposes. My main challenge is trying to implement a 'slideshow' similar to the one demonstrated in this video: https://www.youtube.com/ ...

Implementing the @media rule using Javascript

I'm trying to use JavaScript to add an image dynamically, but I want to remove it when the viewport is 600px or wider. This is my approach so far: var img = document.createElement('img'); // (imagine here all the other fields being defined ...

Looking to update the background color of the items in a sliding door menu using CSS

I'm having trouble changing the background color of my list items in a sliding door menu using CSS. I've successfully changed the left border to green and the text to white, but the background color remains unchanged. Below is the code I'm u ...

How to dynamically display a div in Vue.js depending on the attributes of another element

I have a dilemma with my text container. My goal is to collapse the div if the text length exceeds a certain limit, and then display a button that says "...show more". When this button is clicked, the div should expand. Clicking it again should collapse th ...

I am trying to verify my code, but the messages are not displaying under the username. They only appear under the password field. I am not sure where I have made a mistake

Having trouble with my login form validation using jQuery. Can someone help me fix it? $(document).ready(function() { $("#form1").validate({ rules: { username: { required: true, minlength: 6 }, password: { ...

Bootstrap 5 dropdown toggle displaying incorrect menu

I am currently working on a website project using Bootstrap 5. In the navigation bar of my site, I have implemented a dropdown menu with multiple submenus that dropend. <link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" ...

What is the process for creating a div and its children without inheriting the styles of its parent?

Imagine having the following structure: <div class="building"> <p>...</p> <div class="room"> <p>...</p> </div> </div> <div class="building"> <p>...</p> <div class="room ba ...

Content overflowing beyond the boundaries of the parent DIV in Internet Explorer 6

Take a look at the code snippet below: <div style="width: 50px; border: 1px solid green;"> <div style="position: absolute;"> add whatever text you'd like </div> </div> The display in modern browsers (such as I ...

Unique Floating Bullet Icons Ascending When Enlarged

I'm currently trying to use a star image as a custom bullet point on an <li> element. However, I'm facing the issue where the bottom of the image aligns with the font's baseline, causing the image to be pushed upwards. Is there any sol ...

The JavaScript code will automatically execute loops

Let me illustrate my point with two functions. Function 1 This function triggers a transition when you hover over the square. If you move your mouse off the element and then back on while the transition is still in progress, it will wait until the end of ...

A perfectly organized and justified menu with evenly spaced horizontal list items

I couldn't find a solution to evenly spacing out a series of list items for a menu styled list. After realizing CSS alone wasn't enough, I decided to incorporate some javascript (jQuery). My goal was to have equal padding between each LI without ...