我怎么能居中对齐(水平)一个图像内的容器div?

这里是HTML和CSS。我还为缩略图的其他元素添加了CSS。它以降序运行,所以最高的元素是所有元素的容器,最低的元素是所有元素的内部。

#thumbnailwrapper { color: #2A2A2A; margin-right: 5px; border-radius: 0.2em; margin-bottom: 5px; background-color: #E9F7FE; padding: 5px; border: thin solid #DADADA; font-size: 15px } #artiststhumbnail { width: 120px; height: 108px; overflow: hidden; border: thin solid #DADADA; background-color: white; } #artiststhumbnail:hover { left: 50px } <!--link here--> <a href="NotByDesign"> <div id="thumbnailwrapper"> <a href="NotByDesign"> <!--name here--> <b>Not By Design</b> <br> <div id="artiststhumbnail"> <a href="NotByDesign"> <!--image here--> <img src="../files/noprofile.jpg" height="100%" alt="Not By Design" border="1" /> </a> </div> <div id="genre">Punk</div> </div>

好的,我已经添加了没有PHP的标记,所以应该更容易看到。这两种解决方案在实践中似乎都行不通。顶部和底部的文本不能居中,图像应该在其容器div中居中。容器有溢出隐藏,所以我想看到图像的中心,因为这通常是焦点所在。


当前回答

将图像居中的响应方式可以是这样的:

.center {
    display: block;
    margin: auto;
    max-width: 100%;
    max-height: 100%;
}

其他回答

我发现的最好的事情(似乎在所有浏览器中都有效)是创建一个CSS类,并包括以下参数:

CSS

.center {
    position: relative;          /* where the next element will be automatically positioned */
    display: inline-block;       /* causes element width to shrink to fit content */
    left: 50%;                   /* moves left side of image/element to center of parent element */
    transform: translate(-50%);  /* centers image/element on "left: 50%" position */
}

然后你可以将你创建的CSS类应用到你的标签,如下所示:

HTML

<img class="center" src="image.jpg" />

你也可以通过以下方法将CSS内联到你的元素中:

<img style="position: relative; display: inline-block; left: 50%; transform: translate(-50%);" src ="image.jpg" />

...但我不建议写CSS内联,因为如果你想要改变样式,你必须使用你的居中CSS代码对所有标签进行多次更改。

将图片放入newDiv中。 使包含div的宽度与图像相同。 适用余量:0自动;到newDiv。 这将使div位于容器的中心。

这个也可以

#imagewrapper {
    text-align:center;
}

#imagewrapper img {
    display:inline-block;
    margin:0 5px;
}

您可以使用flex box以最少的代码对齐您的内容

HTML

<div class="image-container">
<img src="https://image.freepik.com/free-vector/modern-abstract-background_1048-1003.jpg" width="100px"> 
</div>

CSS

.image-container{
  width:100%;
  background:green;
  display:flex;

.image-container { 宽度:100%; 背景:绿色; 显示:flex; justify-content:中心; 对齐项目:中心; } < div class = "图像容器" > <img src="https://image.freepik.com/free-vector/modern-abstract-background_1048-1003.jpg" width="100px"> < / div >

Js小提琴链接https://jsfiddle.net/7un6ku2m/

我要大胆地说,以下是你想要的。

注意,我认为问题中不小心遗漏了以下内容(见评论):

<div id="thumbnailwrapper"> <!-- <<< This opening element -->
    <div id="artiststhumbnail">
...

所以你需要的是:

#artiststhumbnail {
    width:120px;
    height:108px;
    margin: 0 auto; /* <<< This line here. */
    ...
}

http://jsfiddle.net/userdude/XStjX/3/