Vishnu Paspunoor Vishnu Paspunoor - 3 months ago 7
CSS Question

Adjusting the container div's size to exactly fit the rendered React component

I am trying to render a component whose style and position are determined based on some cases. In order to do that, I am rendering it in a container which occupies the entire body and the component moves inside it. Instead of doing that, how to make sure the styles of container are the same as that of the component? I don't want the container to occupy the entire body, I only want it to occupy the component.

code:

var componentStyle;
//cases
componentStyle = {}; //some css properties
var MyComponent = React.createClass({
render: function(){
return(
<div style = {componentStyle}>Some content</div>
)
}
})
var container = document.createElement("div");
container.id = "container";
document.body.appendChild(container);
ReactDOM.render(<MyComponent/>,container);


css for container:

#container {
position: absolute;
top:0;left: 0;
font-family: Arial, Helvetica, sans;
background: transparent;
height: 100%;
width: 100%;
z-index:9999999;
}

Answer

This is more like a CSS problem rather than a React problem.

If you don't want the container to occupy the entire body, you should remove width: 100% in your CSS. (I assume your DOM structure is something like:

<body>
  <div id="conatainer">
     <Children />
  </div>
</body>

And if you want it to occupy the component, the css should be

#container {
  display: table;
}

or

(will add extra margin by default)

#container {
  display: inline-block;
}

or

Only in CSS3

#container {
  width: fit-content; 
  /* To adjust the height as well */ 
  height: fit-content;
}

or

Also CSS3 only.

#container {
  width: intrinsic;
}

See more details here

Comments