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


当前回答

.document { 对齐项目:中心; Background-color: hsl(229, 57%, 11%); border - radius: 5 px; 显示:flex; 高度:40像素; 宽度:40像素; } .document img { 显示:块; 保证金:汽车; } < div class = "文件”> <img src="./images/icon-document.svg" alt="icon-document" /> < / div >

其他回答

添加到你的CSS:

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

只是引用了一个子元素,在这个例子中就是图像。

您可以使用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/

使用下面的css命令将图像居中。你必须在图像一开始就给出宽度。

img{
  width: 300px;
  position: fixed;
  left0;
  right:0;

}

我尝试了几种方法。但这种方式对我来说非常合适

<img src="~/images/btn.png" class="img-responsive" id="hide" style="display: block; margin-left: auto; margin-right: auto;" />

使用定位。下面的方法对我很有效……(水平和垂直居中)

缩放到图像的中心(图像填充div):

div{
    display:block;
    overflow:hidden;
    width: 70px; 
    height: 70px;  
    position: relative;
}
div img{
    min-width: 70px; 
    min-height: 70px;
    max-width: 250%; 
    max-height: 250%;    
    top: -50%;
    left: -50%;
    bottom: -50%;
    right: -50%;
    position: absolute;
}

没有缩放到图像的中心(图像不填充div):

   div{
        display:block;
        overflow:hidden;
        width: 100px; 
        height: 100px;  
        position: relative;
    }
    div img{
        width: 70px; 
        height: 70px; 
        top: 50%;
        left: 50%;
        bottom: 50%;
        right: 50%;
        position: absolute;
    }