Is there a more efficient way to center an image inside a floated div

落爺英雄遲暮 提交于 2019-12-23 04:53:28

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!