简体   繁体   中英

Having trouble centering an image in CSS

I am trying to horizontally center an image within a 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. 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. 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

  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; 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.

vertical-align works only in table cells. Try to use Flexbox . The element containing your image should have CSS properties:

display: flex;
align-items: center;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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