Boky Boky - 26 days ago 17
CSS Question

Height auto inside parent with absolute position

My component is something ad follows :

class Test extends React.Component {
outterDivStyles() {
return {
position: "relative",
width: "100%",
overflow: "hidden",
/*height: this.props.height || 200*/
}
}

innerDivStyles(){
return {
position: "absolute",
top: 0,
left: 0,
right: 0,
width: "1000%",
transition: "left .5s",
transitionTimingFunction: "ease"
}
}
render(){
return(
<div>
<div ref="detailsOutterDiv" className="detailsOutterDiv" style={this.outterDivStyles()}>
<div ref="detailsInnerDiv" className="detailsInnerDiv" style={this.innerDivStyles()}>
<div className="slide" ><img src="http://placehold.it/250x200" /></div>
</div>
</div>
</div>
)
}
React.render(<Test />, document.getElementById('container'));


And the css is :

.detailsOutterDiv{
background-color: #f00;
/*height: 200px;*/ //if the height is 200px, then it's ok, but can it be done without that?
width: 300px;
display: block;
}

.slide img{
display: block;
height: auto;
}


Is there any way that the image shows with full height if the parent div has no specific height?

Here is jsfiddle.

QoP QoP
Answer

You have to get the height of detailsInnerDiv after the image loads.

In order to do that, you have to use offsetHeight to get the height, store it in the component state and assign it to detailsOutterDiv.

Something like this

class Test extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      height: 0
    };
  }  
  get outterDivStyles() {
      return {
          position: "relative",
          width: "100%",
          overflow: "hidden",
          /*height: this.props.height || 200*/
      }
  }
  get innerDivStyles(){
      return {
          position: "absolute",
          top: 0,
          left: 0,
          right: 0,
          width: "1000%",
          transition: "left .5s",
          transitionTimingFunction: "ease"
      }
  }
  render(){
      return(
        <div>
              <div
                  ref="detailsOutterDiv"
                  className="detailsOutterDiv"
                  style={{...this.outterDivStyles,height : this.state.height }}
              >
                    <div 
                       ref={node => this.detailsInnerDiv = node}
                       className="detailsInnerDiv"
                       style={this.innerDivStyles}
                    >
                     <div className="slide" >
                       <img 
                         onLoad={() => this.setState({height:this.detailsInnerDiv.offsetHeight})}
                         src="http://placehold.it/250x200"
                       />
                     </div>
                  </div>
              </div>
          </div>
    )
  }
}

jsfiddle

Comments