.box {
width: 300px;
height: 300px;
display: table-cell;
text-align: center;
vertical-align: middle;
border: solid 1px red;
transition: 1s;
}
.box img {
width: 150px;
height: 150px;
}
.box:hover img {
transform: scale(2);
}
<p class="box"><img src="../img/1.jpg"/></p>
img垂直水平居中为什么会有一像素的空隙:
Method 1. Add display:block style to img
Method 2. Add font-size:0 style to .box
https://jsfiddle.net/06m9orbL/
That little gap comes from the baseline. Based on your display:table-cell attribute, it is half of the baseline, because the center of the .box will be aligned with the center of the anonymous line box inside.
You can read w3c’s instructions on display:table and vertical-align https://www.w3.org/TR/CSS22/tables.html#height-layout
http://www.zhangxinxu.com/wordpress/2015/08/css-deep-understand-vertical-align-and-line-height/ This article is excellent
This has nothing to do with vertical-align: middle, but with your display: table-cell. As for the principle, I don’t know yet, but you can solve the gap by adding float: left in the image
The reason why img is an inline block-level element can be solved by setting font-size:0 for the parent element. There are several other solutions. You can search for them. It is inconvenient to type on mobile phones and provide portals
Well, what the guys above said are right, I have also encountered it. . . The rabbit in the picture is so cute, haha!
There is a special discussion on this on the Internet. The general solution is to set the font-size:0 of the parent element. I think it is because of the "bottom line" position of the font. Set to 0 and it will not be affected. Similarly, the centering of text is not completely centered, and it is related to its "bottom line" position.
https://segmentfault.com/q/1010000004076322/a-1020000004078865
Use wildcard *
Methods include setting font-size:0 for the box;
setting display:block for the IMG tag;
or using negative margin. Or writing float. Because after the element floats, it becomes display:bolck