问题
I was wondering if there was a more efficient way to center an image inside a floated div compared to mine. Right now I have it set up so the image is placed inside a p and I center the p. Seeing that extra p tag annoys me way too much :(. Is there anyway I can center the img by itself? Thanks! I listed what I have now down below. Edit: It needs to be vertical and horizontal!
HTML
<div class="filler"><p><img src="images/qualGraphic.png" width="578px" height="256.72px" alt="Quality"/></p></div>
CSS
.filler {
display:table;
width:65.6%;
height:300px;
background-color:#000;
display: table;
float:left;
}
.filler p {
display: table-cell;
vertical-align: middle;
text-align: center;
}
回答1:
To center both horizontally and vertically try adding this to the image.
img {
display: block;
position: absolute;
margin: auto;
top:0;
right: 0;
bottom: 0;
left: 0;
}
The element around the image needs to be positioned relatively i.e.
position: relative
Here's an example with an image inside a floated element
http://jsfiddle.net/xYEuS/
回答2:
Just add the CSS property text-align:center
to the .filler
class. An img
is an inline element so it will center according the the text-align
property.
JS Fiddle: http://jsfiddle.net/CgJZ4/
来源:https://stackoverflow.com/questions/19339958/is-there-a-more-efficient-way-to-center-an-image-inside-a-floated-div