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

2020-05-28 23:50发布

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/

6条回答
地球回转人心会变
2楼-- · 2020-05-29 00:29

You can use display: flex;

DEMO

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

.test img {
  align-self: center;
}
查看更多
闹够了就滚
3楼-- · 2020-05-29 00:43

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>

查看更多
▲ chillily
4楼-- · 2020-05-29 00:46

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>

查看更多
贪生不怕死
5楼-- · 2020-05-29 00:46

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楼-- · 2020-05-29 00:50

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>

查看更多
爷、活的狠高调
7楼-- · 2020-05-29 00:51

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}
查看更多
登录 后发表回答