除特别说明外,本站内容采用创作和非商业用途,请尊重劳动成果。
原文标题: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通过。
如对本文有疑问, 点击进行留言回复!!
清除新版Google Chrome浏览器中表单控件(input,button...)默认的黑色边框
荐 20200714——git/mac配置/项目运行步骤/一些报错
antd 菜单组件 使用时报错:Cannot read property ‘isRootMenu‘ of undefined
CSS|div的style=“background-image: url(img/a.bmp)图片显示不出来
硬件仪表盘账号建立指导(一) --WHQL认证测试结果提交账号(一)
cookie的规范Cookie的不可跨域名性或Cookie与域名的关系
网友评论