How to center image inside a div, using CSS?
This question already has an answer here:
the parent ( #loading
) height is the height of the child element ( img
). because vertical alignment doesn't make sense. set the parent of the greater height, then the inner element can be centered vertically by any available means.
* {
padding: 0;
margin: 0;
}
.overlay {
background: #e9e9e9;
opacity: 0.5;
}
#loading {
display: flex;
height: 100vh;
}
#loading img {
margin: auto;
}
<div class="overlay">
<div id="loading">
<img src="http://placehold.it/160x120">
</div>
</div>
There are a few ways to achieve vertical alignment, many of which get complicated.
One of the simplest fixes involves setting your element to absolute positioning and margins to auto, while defining both the top and the bottom at 0.
#loading {
position: relative;
}
#loading img {
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
margin: auto;
}
Link to jsfiddle.
链接地址: http://www.djcxy.com/p/75754.html上一篇: 水平和垂直居中图像
下一篇: 如何使用CSS在div中居中放置图像?