问题
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.
回答1:
Best solution here is to use :before
pseudo element. Check out this article on centering the unknown, http://css-tricks.com/centering-in-the-unknown/
SEE THE DEMO HERE
body,html {
width: 100%;
height: 100%;
margin: 0;
}
.container {
text-align: center;
background: #ccc;
width: 100%;
height: 100%;
}
.container:before {
content: '';
display: inline-block;
height: 100%;
vertical-align: middle;
margin-right: -0.25em; /* Adjusts for spacing */
}
.image {
display: inline-block;
max-width: 100%;
max-height: 100%;
vertical-align: middle;
padding: 10px 15px;
border: #a0a0a0 solid 1px;
background: #f5f5f5;
}
回答2:
You could use display:table
and display:table-cell
like so Jsfiddle. Though this will just center the image of the child div.
If you need to have a centered div around the image you could always add another div inside of the child
div with the style display: inline-block
example
来源:https://stackoverflow.com/questions/20040156/centering-in-the-unknown