To vertically center this 100px image in this 300px div, you can add a 100px top margin to the image (because 300-100 = 200; 200/2 = 100), and set its horizontal margin to auto
. No need for display: table
etc.
.wrapper4 img {
width: 100px;
height: 100px;
margin: 100px auto;
}
However, that is not very reusable. Will your images always be 100px? Will they always be square?
If not, you have to account for centering landscape & portrait images of different sizes.
The easiest way to do this, with modern web browsers (anything newer than IE9 from about 2013) is to use Flexbox, as explained in this answer by tombul.
You could apply the flex rules directly to your div
element, but again this is not very reusable. Another option is to create a CSS class for an element that centers its contents in a flex container. This CSS class is then applied in the HTML. The wrapper
class now just handles the dimensions and appearance of the wrapper; the wrapper img
class just handles the dimensions and appearance of the image. The alignment of the image is controlled by the centerFlex
class. If you wanted multiple images with left, centered, or right-justification, you could create & apply similar rules to accomplish that.
FYI, you can include all margins with the shorthand syntax margin: top right bottom left
, or in pairs margin: top&bottom left&right
.wrapper4 {
width: 300px;
height: 300px;
border: 1px solid green;
margin: 0px auto;
}
.centerFlex {
align-items: center;
display: flex;
justify-content: center;
}
.wrapper4 img {
width: 100px;
height: 100px;
}
<!DOCTYPE html>
<html>
<head>
<meta name="description" content="垂直居中demo" />
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body>
<div class="wrapper4 centerFlex">
<img src="http://listenwallstreet.com/wp-content/uploads/2016/03/xiaogou.jpg" alt="小狗">
</div>
</body>
</html>