简体   繁体   English

在CSS中将图片居中时遇到问题

[英]Having trouble centering an image in CSS

I am trying to horizontally center an image within a div. 我正在尝试在div中水平居中放置图像。 However, I haven't been able to. 但是,我没有。 I've tried setting the vertical-align to middle and the margin to auto, 0 auto, and every variation I can think of. 我试过将vertical-align设置为中间,将margin设置为auto,将auto设置为0,并且可以想到所有变化。 Nothing works. 什么都没有。 Here is the code for how it is currently set up: 这是当前设置方式的代码:

img {
border: 0;
margin: 0 auto;
}

.intro img {
border-radius: 50%;
vertical-align: middle;
padding: 10px;
}

The image is in the intro div. 该图像位于简介div中。 Any advice you can give would be helpful. 您可以提供的任何建议都会有所帮助。

If you want to center your image both horizontally & vertically, this should do the trick : 如果你想同时在水平和垂直居中你的形象,这应该做的伎俩:

  .intro { display: table; width: 500px; /* works with any width */ height: 150px; /* works with any height */ background: #ccc; } .imgcontainer { display: table-cell; vertical-align: middle; text-align: center; } img { background: #fff; padding: 10px; border-radius: 50%; } 
 <div class="intro"> <div class="imgcontainer"> <img src="http://s.gravatar.com/avatar/bf4cc94221382810233575862875e687?r=x&s=50" /> </div> </div> 

Use position:relative in parent .intro and use the code shown below in img , it will work with any width and height 使用.intro position:relative并使用下面的img所示的代码,它可以在任何widthheight

  display:block;
  margin:auto;
  position: absolute;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0

Snippet 片段

 .intro { border: dashed red; /* demo */ display:inline-block; /* demo */ vertical-align:top; /* demo */ position: relative } .intro img { border-radius: 50%; vertical-align: middle; display: block; margin: auto; position: absolute; top: 0; left: 0; bottom: 0; right: 0 } .intro:first-of-type { width: 200px; height: 200px; } .intro:last-of-type { width: 400px; height: 300px; } 
 <div class="intro"> <img src="//lorempixel.com/100/100" /> </div> <div class="intro"> <img src="//lorempixel.com/100/100" /> </div> 

The css style margin: 0 auto; CSS样式margin: 0 auto; should do the horizontal part of the trick. 应该做技巧的水平部分。 For the vertical part you also need to take care of the parent. 对于垂直部分,您还需要照顾父母。 Look at How to vertically align an image inside div for more info. 有关更多信息,请参见如何在div中垂直对齐图像

vertical-align works only in table cells. vertical-align仅在表格单元格中有效。 Try to use Flexbox . 尝试使用Flexbox The element containing your image should have CSS properties: 包含图像的元素应具有CSS属性:

display: flex;
align-items: center;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM