我怎么能居中对齐(水平)一个图像内的容器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中居中。容器有溢出隐藏,所以我想看到图像的中心,因为这通常是焦点所在。


当前回答

#artiststhumbnail a img {
    display:block;
    margin:auto;
}

这是我的解决方案:http://jsfiddle.net/marvo/3k3CC/2/

其他回答

#artiststhumbnail a img {
    display:block;
    margin:auto;
}

这是我的解决方案:http://jsfiddle.net/marvo/3k3CC/2/

如果您必须内联执行此操作(例如使用输入框时), 这里有一个对我有用的小技巧:把你的周围围起来(这里是图片链接) 在style="text-align:center"的div中

<div style="text-align:center">

<a title="Example Image: Google Logo" href="https://www.google.com/" 
target="_blank" rel="noopener"><img src="https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png" alt="Google Logo. Click to visit Google.com" border="0" data-recalc-dims="1" /></a>

<h6><strong>This text will also be centered </strong></h6>

</div> /* ends centering style */

是的,这样的代码可以正常工作

<div>
 <img/>
</div>

提醒大家一下,图像的样式

object-fit : *depend on u*

所以最终的代码就像例子一样

div { 显示:flex; justify-content:中心; 对齐项目:中心; } Div img { object-fit:包含; } < span style=" font - family:宋体;"> <img src="https://img.joomcdn.net/9dd32cbfa0cdd7f48ca094972ca47727cd3cd82c_original.jpeg" alt="" srcset="" style=" 这个特性:50%; 高度:7.5快速眼动; 宽度:7.5快速眼动; ”object-fit:包含;/> < / div >

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

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

<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/

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