Note that there are some explanatory texts on larger screens.

plurals
  1. POCentering in the unknown
    text
    copied!<p>I would like to center and clamp the dimensions of a child div inside its parent.</p> <pre><code>&lt;style type='text/css'&gt; .parent { width: 100%; height: 100%; } .child { max-width: 100%; max-height: 100%; } &lt;/style&gt; &lt;div class="parent"&gt; &lt;div class="child"&gt; &lt;img src='dog.jpg' /&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>Here are the constraints:</p> <ul> <li>The parent div is set to occupy the entire screen (of unknown size), so <code>width:100%</code> and <code>height:100%</code>.</li> <li>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. </li> <li>The width and height of the child div must be constrained to the size of the parent, so <code>max-width: 100%</code> and <code>max-height: 100%</code>. </li> <li>The child div must be vertically and horizontally centered inside the parent.</li> <li>Ideally, this should work without javascript.</li> <li>IE can be left unsupported :)</li> </ul> <p>I've tried all the techniques listed in this excellent article, <a href="http://codepen.io/shshaw/full/gEiDt#Comparison-Table" rel="nofollow noreferrer">'Absolute Centering in CSS' </a>, and none of them pan out. Here's why:</p> <ul> <li><strong>Absolute centering</strong>: In order for this technique to work with a child of unknown size, you must set <code>display:table</code> 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.</li> <li><strong>Negative margins</strong>: Doesn't allow for variable height.</li> <li><strong>Transforms</strong>: Undesirable because it can result in blurry rendering.</li> <li><strong>Table-cell</strong>: Fails for the same reason that absolute centering fails, i.e. table rendering.</li> <li><strong>Inline-block</strong>: Doesn't work in the important case where the child is 100% width.</li> <li><strong>Flexbox</strong>: Works well until a window resize occurs, at which point you have to force a Webkit redraw to propagate the centering changes. This <a href="https://stackoverflow.com/questions/3485365/how-can-i-force-webkit-to-redraw-repaint-to-propagate-style-changes">hack</a> does the job, but it's still a hack. I want to believe there's a more elegant solution to this.</li> </ul>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload