简体   繁体   中英

Keep fixed aspect ratio for div

I have a CSS Grid on my React app. The columns are the correct width already. In one of the cells of this grid, I want to add a <div> that maintains a fixed aspect ratio while stretching out (or shortening to) the width of the cell; meaning, the height should change responsively.

Note: because this <div> is part of a reusable component, I pass in the height and width of the <div> as inline styles for maxHeight and maxWidth. I want this to work even if there is no content within the div, as it is part of an animation sequence, and I need that space to be vacant.

JS:

<div className="img-container" style={{maxHeight: props.dimensions.height, maxWidth: props.dimensions.width}}>  (content goes here)  </div>

I then apply CSS classes to "img-container" to set width to 100%. Also to set background to 'red' just to see if it works.

CSS:

.img-container { width: 100%; background: red; }

But alas, no red shows up. I can see in dev tools that the width works, however there is no red on the screen as there is no height. Can someone clue me into what I can do to create this div with a red background of a fixed aspect ratio, that will resize up or down to fit the width of the cell of the grid?

your div tag structure is incorrectly specified. you need like this:

<div className="img-container" style={{maxHeight: props.dimensions.height, maxWidth: props.dimensions.width}}>  (content goes here)  </div>

You can achive the desired results by adding a child div with minimum width and minimum height to maintain the aspect ratio.

<div className="img-container" style={...styles}>   
   <div className='inner-div'></div>
</div>

CSS

.inner-div {
   min-height: 200px;
   min-width: 200px; 
}

//change the above values according to your requirements.

Found the answer!

Let's work on my example provided, however change the JS and CSS as such, and also include an inner div with className 'img-inner' as an example.

JS:

Let's also insert paddingTop as a prop.

<div className="img-container" style={{maxHeight: props.dimensions.height, maxWidth: props.dimensions.width, paddingTop: `${props.dimensions.height/props.dimensions.width*100}%`}}>  (content goes here, e.g. a div with className="img-inner")  </div>

CSS:

.img-container { width: 100%, position: relative }

.img-inner { position: absolute, top: 0, bottom: 0, left: 0, right: 0 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM