5

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;
}
Diablo3093
  • 963
  • 4
  • 15
  • 26
  • you can set the container `display` property to `inline`. This will make the container to take up the width and height of its contents. – z0mBi3 Aug 26 '16 at 10:39

1 Answers1

7

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="container">
     <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

MiguelSlv
  • 14,067
  • 15
  • 102
  • 169
Henry Chen
  • 610
  • 7
  • 6