I would like to center and clamp the dimensions of a child div inside its parent.
<style type='text/css'>
.parent {
width: 100%;
height: 100%;
}
.child {
max-width: 100%;
max-height: 100%;
}
</style>
<div class="parent">
<div class="child">
<img src='dog.jpg' />
</div>
</div>
Here are the constraints:
- The parent div is set to occupy the entire screen (of unknown size), so
width:100%
andheight:100%
. - The width and height of the child div are unknown. In one use case, the child div contains an image. In another, it contains a video.
- The width and height of the child div must be constrained to the size of the parent, so
max-width: 100%
andmax-height: 100%
. - The child div must be vertically and horizontally centered inside the parent.
- Ideally, this should work without javascript.
- IE can be left unsupported :)
I've tried all the techniques listed in this excellent article, 'Absolute Centering in CSS' , and none of them pan out. Here's why:
- Absolute centering: In order for this technique to work with a child of unknown size, you must set
display:table
on the child. You can then constrain the max-width of the child's contents, but not the max-height, because by CSS 2.1 rules, tables render to fit their contents. - Negative margins: Doesn't allow for variable height.
- Transforms: Undesirable because it can result in blurry rendering.
- Table-cell: Fails for the same reason that absolute centering fails, i.e. table rendering.
- Inline-block: Doesn't work in the important case where the child is 100% width.
- Flexbox: Works well until a window resize occurs, at which point you have to force a Webkit redraw to propagate the centering changes. This hack does the job, but it's still a hack. I want to believe there's a more elegant solution to this.