问题
Trying to horizontally center and crop (if necessary) a div inside of another div.
It's possible to achieve this same effect with a background image, but in this case my content is not a single image.
Fiddle: http://jsfiddle.net/7aMhY/1/
HTML:
<div class="poster_container">
<div class="poster_row">
<div class="poster" style="width: 210px;">1</div>
<div class="poster" style="width: 210px;">2</div>
<div class="poster" style="width: 210px;">3</div>
<div class="poster" style="width: 210px;">4</div>
<div class="poster" style="width: 210px;">5</div>
</div>
</div>
CSS:
.poster_container {
text-align: center;
border: dotted;
border-color: red;
background-color: #0ff;
margin: auto;
overflow:hidden;
}
.poster_row {
text-align: center;
margin: auto;
display: inline-block;
white-space:nowrap;
oveterflow:hidden;
border: dotted;
border-color: blue;
max-width: 100%;
}
.poster {
border: dotted;
display: inline-block;
border-color: green;
background-color: green;
height: 315px;
font-size:280px;
color: white;
}
As long as the poster_container div is wider than the poster_row div, the content is centered. But once poster_row is wider, it crops but its content is flush left and cropped on the right only.
I'm trying to have the inner poster_row div center and crop equally from both sides. The outer div will be 100% of the viewport, so its width is arbitrary. Ideally I'd like the inner div to have arbitrary width as well, so I can easily swap out content without changing the CSS.
回答1:
I think I got it :
I let you add your prefixes and remove the max-width value
.poster_row {
margin: auto;
text-align: center;
display: inline-block;
white-space:nowrap;
overflow:hidden;
border: dotted;
border-color: blue;
position: absolute;
left: 50%;
transform:translate(-50%,0);
}
回答2:
if the width of your poster_row isn't about to change add:
.poster_row {
text-align: center;
margin: auto;
display: inline-block;
white-space:nowrap;
overflow:hidden;
border: dotted;
border-color: blue;
position:absolute;
left: 50%;
margin-left: -525px;
width: 1050px;
}
otherwise you have to calculate the width and margin-left with Js
来源:https://stackoverflow.com/questions/17473954/how-to-horizontally-center-crop-div-inside-other-div