CSS垂直对齐问题 [英] CSS vertical alignment problem

查看:164
本文介绍了CSS垂直对齐问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下示例:(。



这将适用于所有不错的浏览器,甚至在IE8 / 9, t工作在IE6 / 7。解决这个问题的技术应该在IE6 / 7中工作:在 a ,设置显示 block 并将 line-height 0 改为 78px (我不完全清楚为什么 80px 使它向下移动一个像素,但它确实;如果我想足够长,我可能弄清楚为什么),并将 vertical-align:middle 转移到 img 最终结果: http://jsfiddle.net/jESsA/44/


Consider the following example: (live demo here)

HTML:

<div id="outer_wrapper">
    <div class="wrapper">
        <a><img src="http://img.brothersoft.com/icon/softimage/s/smiley.s_challenge-131939.jpeg" /></a>
    </div>
    <div class="wrapper">
        <a><img src="http://assets.test.myyearbook.com/pimp_images/home_page/icon_smiley.gif" /></a>
    </div>
    <div class="wrapper">
        <a><img src="http://thumbs3.ebaystatic.com/m/mvHqVR-GDRQ2AzadtgupdgQ/80.jpg" /></a>
    </div>
    <div class="wrapper">
        <a><img src="http://upload.wikimedia.org/wikipedia/commons/thumb/f/fa/718smiley.png/60px-718smiley.png" /></a>
    </div>
</div>

CSS:

#outer_wrapper {
    background-color: #bbb;
    width: 350px;
}
.wrapper {
    display: inline-block;
    border: 1px solid black;
    width: 90px;
    height: 100px;
    text-align: center;
    margin-right: 20px;
}
a {
    display: inline-block;
    width: 80px;
    height: 80px;
    border: 1px solid red;
}

The output is:

  1. Why the black wrappers are not vertically aligned ? How could I fix that ?
  2. The images are horizontally centered in the red boxes. How could I vertically center them ?

Please do not change the HTML, if possible.

解决方案

Observe that it is the base of the images which are aligned. This is to do with the vertical-align; if you use a value for vertical-align on .wrapper other than baseline, like top, middle or bottom, it will fix it. (The difference between these will only be apparent if you put some text inside the div as well.)

Then you want to centre the images in their 80x80 spots. You can do that with display: table-cell and vertical-align: middle on the a (and add line-height: 0 to fix a couple more issue). You can then play further with mixing these groups of styles in the a tag, the .wrapper, or even throwing away the .wrapper if it isn't necessary (it would only be needed - if it is at all - if you're putting text in with it).

Result, with no further tweaks than what I've mentioned here: http://jsfiddle.net/jESsA/38/.

This will work on all decent browsers, and even on IE8/9, but it won't work on IE6/7. A technique for solving this which should work in IE6/7 is this: on the a, set display to block and alter the line-height from 0 to 78px (I'm not entirely clear on why 80px makes it shift down one pixel, but it does; if I thought about it long enough I could probably figure out why), and shift the vertical-align: middle to the img child. Final result: http://jsfiddle.net/jESsA/44/

这篇关于CSS垂直对齐问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆