How to make an image center (vertically & horizont

2018-12-31 04:47发布

I have a div 200 x 200 px. I want to place a 50 x 50 px image right in the middle of the div.

How can it be done?

I am able to get it centered horizontally by using text-align: center for the div. But vertical alignment is the issue..

标签: html css
30条回答
其实,你不懂
2楼-- · 2018-12-31 05:28

@sleepy You can easily do this using the following attributes:

#content {
  display: flex;
  align-items: center;
  width: 200px;
  height: 200px;
  border: 1px solid red;
}

#myImage {
  display: block;
  width: 50px;
  height: 50px;  
  margin: auto;
  border: 1px solid yellow;
}
<div id="content">
  <img id="myImage" src="http://blog.w3c.br/wp-content/uploads/2013/03/css31-213x300.png">
</div>

References: W3

查看更多
浮光初槿花落
3楼-- · 2018-12-31 05:29

Vertical-align is one of the most misused css styles. It doesn't work how you might expect on elements that are not td's or css "display: table-cell".

This is a very good post on the matter. http://phrogz.net/CSS/vertical-align/index.html

The most common methods to acheive what you're looking for are:

  • padding top/bottom
  • position absolute
  • line-height
查看更多
笑指拈花
4楼-- · 2018-12-31 05:29

This worked for me. Add this to image css:

img
{
   display: block;
   margin: auto;
}
查看更多
柔情千种
5楼-- · 2018-12-31 05:30

We Can Easily achieve this using flex. no need of background image

enter image description here

<!DOCTYPE html>
<html>
<head>
   <style>
      #image-wrapper{
         width:500px;
         height:500px;
         border:1px solid #333;
         display:flex;
         justify-content:center;
         align-items:center;
      }
   </style>
</head>
<body>

<div id="image-wrapper">
<img id="myImage" src="http://blog.w3c.br/wp-content/uploads/2013/03/css31-213x300.png">
</div>

</body>
</html>

查看更多
千与千寻千般痛.
6楼-- · 2018-12-31 05:31

I've found that Valamas' and Lepu's answers above are the most straightforward answers that deal with images of unknown size, or of known size that you'd rather not hard-code into your CSS. I just have a few small tweaks: remove irrelevant styles, size it to 200px to match the question, and add max-height/max-width to handle images that may be too large.

div.image-thumbnail
{
    width: 200px;
    height: 200px;
    line-height: 200px;
    text-align: center;
}
div.image-thumbnail img
{
    vertical-align: middle;
    max-height: 200px;
    max-width: 200px;
}
查看更多
ら面具成の殇う
7楼-- · 2018-12-31 05:32
.container {
height: 200px;
width: 200px;
float:left;
position:relative;
}
.children-with-img {
position: absolute;
width:50px;
height:50px;
left:50%;
top:50%;
transform:translate(-50%);
}
查看更多
登录 后发表回答