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.
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.
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>
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>
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>
You can use display: flex;
.test {
display: flex;
justify-content: center;
background-color: orange;
width: 700px;
height: 700px;
}
.test img {
align-self: center;
}
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/
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}