CSS解决未知高度垂直居中的问题_CSS/HTML

WBOY
Release: 2016-05-16 12:10:54
Original
1411 people have browsed it

除特别说明外,本站内容采用创作共用授权署名和非商业用途,请尊重劳动成果。

原文标题:Vertical Centering in CSS

副标题:Yuhu's Definitive Solution with Unknown Height

翻译:forestgan

尽管有CSS的vertical-align特性,但是并不能有效解决未知高度的垂直居中问题(在一个DIV标签里有未知高度的文本或图片的情况下)。

标准浏览器如Mozilla, Opera, Safari等.,可将父级元素显示方式设定为TABLE(display: table;) ,内部子元素定为table-cell (display: table-cell),通过vertical-align特性使其垂直居中,但非标准浏览器是不支持的。

非标准浏览器只能在子元素里设距顶部50%,里面再套个元素距顶部-50% 来抵消。

CSS
body {padding: 0; margin: 0;}
body,html{height: 100%;}
#outer {height: 100%; overflow: hidden; position: relative;width: 100%; background:ivory;}
#outer[id] {display: table; position: static;}
#middle {position: absolute; top: 50%;} /* for explorer only*/
#middle[id] {display: table-cell; vertical-align: middle; position: static;}
#inner {position: relative; top: -50%;width: 400px;margin: 0 auto;} /* for explorer only */
div.greenBorder {border: 1px solid green; background-color: ivory;}

XHTML






以上CSS代码的优点是没有hacks,采用了IE不支持的CSS2选择器#value[id]。

CSS2选择器#value[id]相当于选择器#value,但是Internet Explorer不支持这种类型的选择器。同样地.value[class],相当于.value,这些只有标准浏览器能读懂。

测试:Firefox1.5、Opera9.0、IE6.0、IE5.0通过。

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
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!