I want to set its width to 15% of the window width in my Javas...">

Set div width with D3

I have created divin my html,

<div id="search"></div>

I want to set its width to 15% of the window width in my Javascript. I am trying to use D3 for this:

var width = 0.15 * window.innerWidth,
    height = 0.95 * window.innerHeight;

var searchcolumn = d3.select("#search")
                    .attr("width", width)
                    .attr("height", height);

I see in the DOM, the width and height of my div has been changed: enter image description here

However, the displayed html is divsimple 10px x 10px.

enter image description here

Why is this happening? I don't have CSSone that overwrites the size div. How to set mine divto my desired width?

+4
source share
3 answers

Try:
d3.select("#search") .style("height", height) .style("width", width); >

+2
source

This is an old post, but for those who want to solve this, the following will work:

var width = 0.15 * window.innerWidth,
    height = 0.95 * window.innerHeight;

var searchcolumn = d3.select("#search")
                    .style("width", width + 'px')
                    .style("height", height + 'px');

: + 'px'; .attr .style CSS, .

:

var data = [10,12,6,8,15];

var svg = d3.select('body')
//.append('svg')
.attr('width', 500).attr('height', 500);

var width = 0.15 * window.innerWidth,
    height = 0.95 * window.innerHeight;
     
svg.selectAll('div')
  .data(data)
  .enter().append('div')
  .attr('class','divs')
  .attr('x', function(d,i) { d.clicked=false; return 100+100*i; })
  .attr('y', function(d,i) { return 0; })
  .style('width', width + 'px')
  .style('height',height +'px')
  .attr('background-color', function() { return 'red'; }) 

  .text(function(d){ return d;})
.divs { 
  background: blue;  
  display:inline-block;
  float:left;
  margin:5px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
Hide result
+2

You can simply do the following if you want to set multiple style attributes instead of repeating style(" ", " ") ntimes:

d3.select("#search").style({
  'height': height+'px',
  'width': width+'px'
});

Hope this helps.

+1
source

All Articles