我想要一个通过百分比的op-margin的子div. y位置应为父div的50%.但它在某种程度上更多.为什么不是50%?
HTML
<div class="content"> <header></header> </div>
CSS
.content { width: 300px; height: 200px; background: blue; position: relative; clear: both; } .content header { width: 100px; height: 100px; margin-top: 50%; background: red; position: relative; float: left; }
解决方法
这是因为当以百分比形式显示顶部/底部边距和填充时,这些值将被视为父元素的小数宽度,而不是高度.根据
W3C definition:
The [margin] percentage is calculated with respect to the width of the
generated Box’s containing block. Note that this is true for
‘margin-top’ and ‘margin-bottom’ as well. If the containing block’s
width depends on this element,then the resulting layout is undefined
in CSS 2.1.
此问题之前已在StackOverflow – see here中得到解决.
建议:如果要将元素垂直放置在中心,可以使用以下技巧:
>绝对定位子元素
>声明父级的维度,使父级的维度不依赖于子级的维度
>将子元素从顶部放置50%
>使用CSS 2D翻译的漂亮技巧.
这是你的小提琴中修改过的CSS有效:
.content header { width: 100px; height: 100px; top: 50%; background: red; position: absolute; -webkit-transform: translate(0,-50%); transform: translate(0,-50%); }
原文地址:https://www.jb51.cc/html/225210.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。