search

Home  >  Q&A  >  body text

css3 - img垂直水平居中问题

.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垂直水平居中为什么会有一像素的空隙:

阿神阿神2866 days ago1337

reply all(11)I'll reply

  • PHP中文网

    PHP中文网2017-04-17 11:37:56

    Method 1. Add display:block style to img
    Method 2. Add font-size:0 style to .box

    reply
    0
  • 阿神

    阿神2017-04-17 11:37:56

    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

    reply
    0
  • 巴扎黑

    巴扎黑2017-04-17 11:37:56

    http://www.zhangxinxu.com/wordpress/2015/08/css-deep-understand-vertical-align-and-line-height/ This article is excellent

    reply
    0
  • 天蓬老师

    天蓬老师2017-04-17 11:37:56

    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

    reply
    0
  • 大家讲道理

    大家讲道理2017-04-17 11:37:56

    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

    reply
    0
  • PHPz

    PHPz2017-04-17 11:37:56

    Well, what the guys above said are right, I have also encountered it. . . The rabbit in the picture is so cute, haha!

    reply
    0
  • 黄舟

    黄舟2017-04-17 11:37:56

    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.

    reply
    0
  • 大家讲道理

    大家讲道理2017-04-17 11:37:56

    https://segmentfault.com/q/1010000004076322/a-1020000004078865

    reply
    0
  • 黄舟

    黄舟2017-04-17 11:37:56

    Use wildcard *

    *{
        margin:0;
        padding:0;
    }

    reply
    0
  • 黄舟

    黄舟2017-04-17 11:37:56

    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

    reply
    0
  • Cancelreply