html - CSS图片居中问题?
天蓬老师
天蓬老师 2017-04-17 13:33:05
0
5
1156

html如下:

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

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

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

新手真心求问~?

天蓬老师
天蓬老师

欢迎选择我的课程,让我们一起见证您的进步~~

reply all(5)
迷茫

The header is not closed, right?

刘奇

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;
}
伊谢尔伦

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

伊谢尔伦

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

PHPzhong

To set display:table-cell in span

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!