How to center an image in the middle of a div? [duplicate]

血红的双手。 提交于 2020-02-18 05:39:08

问题


I need to center an image in a middle of a div.

<div class="main">
    <img...>
</div>

In the example below the image is centered, but not in the middle.

https://jsfiddle.net/web_garaux/tng7db0k/


回答1:


Simple and easy method to do this,

.test {
  background-color: orange;
  width: 700px;
  height: 700px;
  display:flex;
  align-items:center;
  justify-content:center;
}
<div class="test">
<img src="http://via.placeholder.com/350x150">
</div>



回答2:


To vertically center your div, you can use positioning. Just apply

position: relative;
top: 50%;
transform: translateY(-50%);

to your image, and it will be vertically centered.

.test {
  background-color: orange;
  width: 700px;
  height: 700px;
  text-align: center;
}

.test>img {
  position: relative;
  top: 50%;
  transform: translateY(-50%);
}
<div class="test">
  <img src="http://via.placeholder.com/350x150">
</div>



回答3:


You can use the simplest way -> display: table-cell; which allows you to use vertical-align attribute

.test {
  background-color: orange;
  width: 500px;
  height: 300px;
  text-align: center;
  display: table-cell;
  vertical-align: middle;
}
<div class="test">
<img src="http://via.placeholder.com/350x150">
</div>



回答4:


You can use display: flex;

DEMO

.test {
  display: flex;
  justify-content: center;
  background-color: orange;
  width: 700px;
  height: 700px;
}

.test img {
  align-self: center;
}



回答5:


Cleanest solution would be to make your div display:flex and align/justify content to center.

.test {
  background-color: orange;
  width: 700px;
  height: 700px;
  display: flex;
  align-items: center;
  justify-content: center;
} 

Your updated Fiddle: https://jsfiddle.net/y9j21ocr/1/

More reads on flexbox (recommended)




回答6:


It is really easy if you can give image as background to div

.test {
  background-color: orange;
  width: 700px;
  height: 700px;
  text-align: center;
  background-repeat: no-repeat;
  background-position: center center;
}

<div class="test" style="background-image:url(http://via.placeholder.com/350x150);">
</div>

If you dont want to use inline style you can do

<div class="test">
  <img src="http://via.placeholder.com/350x150">
</div>

.test > img{
  position:absolute;
  top:50%;
  left:50%;
  transform:translate(-50%,-50%);
}
.test{position: relative}


来源:https://stackoverflow.com/questions/44500404/how-to-center-an-image-in-the-middle-of-a-div

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!