search

Home  >  Q&A  >  body text

html - CSS图片居中问题?

html如下:

<header class="header">
    <span class="logo">
        <img src="img/baidu.png"/>
    </span>

CSS中为什么我在<header>和<span>中设置了vertical-align:middle;都不会使图片产生居中效果,

而用设置为表格的方式才能生效,

新手真心求问~?

天蓬老师天蓬老师2785 days ago1202

reply all(5)I'll reply

  • 迷茫

    迷茫2017-04-17 13:35:05

    The header is not closed, right?

    reply
    0
  • 怪我咯

    怪我咯2017-04-17 13:35:05

    The solution is as follows. Add a span in front of img

    <p>
      <span></span>
      <img src="img/star.png" alt="">
    </p>

    Set attributes for span

    span{
    height:100%;
    display:inline-block;
    vertical-align:middle;
    }
    p{
    border:1px solid #333;
    width:500px;
    height:400px;
    text-align:center;
    }
    img{
    vertical-align:middle;
    }

    reply
    0
  • 伊谢尔伦

    伊谢尔伦2017-04-17 13:35:05

    vertical-align is calculated based on the baseline of the element baseline and the baseline of the parent element. It is relative to the row where the element itself is located. This attribute defines the baseline of the inline element relative to the element Vertical alignment of the baseline of row .

    <p class="parent">
        <span class="child">
            123456
            <img class="middle" src="xxx" />
        </span>
    </p>
    
    <style>
        .middle {
            vertical-align: middle;
        }
    </style>

    At this time, you set .child as an inline block-level element, and then set the height to it. This height is not the row height of the row where the img itself is located, so in this case, you will not achieve what you want. Effective. Regardless of whether .child has a height set, the img of vertical-align is only relative to its own row.

    The vertical-align CSS property specifies the vertical alignment of an inline or table-cell box. -- MDN

    Of courseinline-block that’s also possible.

    Chestnut
    plunker

    reply
    0
  • 伊谢尔伦

    伊谢尔伦2017-04-17 13:35:05

    vertical-align:middle centers the child elements and can only take effect when the table cell or element display attribute is set to table-cell. Here is a video tutorial to clear up your doubts. http://www.imooc.com/learn/542

    reply
    0
  • PHPz

    PHPz2017-04-17 13:35:05

    To set display:table-cell in span

    reply
    0
  • Cancelreply