css3 - img垂直水平居中问题
阿神
阿神 2017-04-17 11:35:56
0
11
1288
.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垂直水平居中为什么会有一像素的空隙:

阿神
阿神

闭关修行中......

reply all(11)
洪涛

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

Peter_Zhu

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

PHPzhong

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 *

*{
    margin:0;
    padding:0;
}
黄舟

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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template