Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
303 views
in Technique[技术] by (71.8m points)

html - CSS: Vertically align div when no fixed size of the div is known

How do I align a <div> which contains an image (or flash) vertically with CSS. Height and width are dynamic.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This is a pure CSS2 solution for horizontally and vertically centering without known sizes of either container nor child. No hacks are involved. I discovered it for this answer and I also demonstrated it in this answer.

The solution is based on vertical-align: middle in conjunction with line-height: 0, which parent has a fixed line-height.

The HTML:

<span id="center">
    <span id="wrap">
        <img src="http://lorempixum.com/300/250/abstract" alt="" />
    </span>
</span>

And the CSS:

html,
body {
    height: 100%;
    width: 100%;
    padding: 0;
    margin: 0;
    overflow: hidden;
}
#center {
    position: relative;
    display: block;
    top: 50%;
    margin-top: -1000px;
    height: 2000px;
    text-align: center;
    line-height: 2000px;
}    
#wrap {
    line-height: 0;
}
#wrap img {
    vertical-align: middle;
}

Tested on Win7 in IE8, IE9, Opera 11.51, Safari 5.0.5, FF 6.0, Chrome 13.0.

The only caveat is IE7, for which the two innermost elements have to declared at one line, as demonstrated in this fiddle:

<span id="center">
    <span id="wrap"><img src="http://lorempixum.com/300/250/abstract" alt="" /></span>
</span>

Note that the span's are also required for IE7. In every other browser, the span's may be div's.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...