Centering floated images in div

微笑、不失礼 提交于 2019-12-11 00:29:24

问题


I'm trying to center floated images on my page, but I can't get it to work. Here is my code

.imcontainer {
    text-align:center;
    display:inline-block;
}.float {
    float: left;
    font-size: small;
    height: auto;
    margin: 5px 7px 0 3px;
    width: auto;
}

HTML

<div class="imcontainer">
    <div class="float"><img width="70px" height="70px" src="image.jpg"></div>
    <div class="float"><img width="70px" height="70px" src="image.jpg"></div>
    <div class="float"><img width="70px" height="70px" src="image.jpg"></div>
    <div class="float"><img width="70px" height="70px" src="image.jpg"></div>
    <div class="float"><img width="70px" height="70px" src="image.jpg"></div>
</div>

How can I fix this problem?


回答1:


You can center the container and inline-block the children to achieve the desired layout.

.imcontainer {
    text-align:center; /* center everything in the container */
}

.float { /* not really float any more so best to rename this */
    display:inline-block; /* so the children on the same line */
    font-size: small;
    height: auto;
    margin: 5px 7px 0 3px;
    width: auto;
}

I would definitely correct the HTML as well to make it valid

<div class="imcontainer">
    <div class="float"><img width="70" height="70" alt="" src="image.jpg"/></div>
    <div class="float"><img width="70" height="70" alt="" src="image.jpg"/></div>
    <div class="float"><img width="70" height="70" alt="" src="image.jpg"/></div>
    <div class="float"><img width="70" height="70" alt="" src="image.jpg"/></div>
    <div class="float"><img width="70" height="70" alt="" src="image.jpg"/></div>
</div>



回答2:


Try this:

.float {
    float: left;
    font-size: small;
    height: auto;
    margin: 5px 7px 0 3px;
    width: 100px;
    text-align: center;
}



回答3:


Use this CSS:

.imcontainer {
    text-align: center;
}
.float {
    display: inline-block;
    font-size: small;
    height: auto;
    margin: 5px 7px 0 3px;
    width: auto;
}



回答4:


I think you want like this

http://jsfiddle.net/JZxxG/

Your CSS

.imcontainer {
    text-align: center;
    display: inline-block;
    width: 100%
}
.float {
    float: left;
    font-size: small;
    height: auto;
    width: 100%;
}



回答5:


@andyb has given a perfect solution, but if you are still not satisfied, you can try by adding display: table-cell; text-align: center; to your float, not to your imcontainer, and if you want some gap, add padding value.



来源:https://stackoverflow.com/questions/15950007/centering-floated-images-in-div

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