【发布时间】:2014-12-21 16:57:12
【问题描述】:
我试图让一个可变大小的父元素中的元素既是方形的,又位于左侧并垂直居中。我宁愿只在 CSS 中执行此操作并避免使用 javascript。
这会生成一个宽度正确且水平位置正确(距左侧 10%)的框,但会填充其父级的高度。 http://jsfiddle.net/6tvsmLnp/
<div id="d1">
<div id="d2"></div>
</div>
<style type="text/css">
*
{
margin:0;padding:0;
}
div#d1
{
width: 90vw;
height: 50.625vw;
background: pink;
max-height: 90vh;
max-width: 177.78vh;
margin: auto;
position: absolute;
top:0;bottom:0;
left:0;right:0;
}
div#d2
{
background: blue;
width:10%;
top: 0;
bottom: 0;
left: 10%;
position:absolute;
margin:auto;
}
#d2:before{
content: "";
display: inline-block;
padding-top: 100%; /* initial ratio of 1:1*/
}
</style>
将#d2 的position 更改为相对使其成为所需的大小和纵横比,但位于其父级的顶部和中心的右侧。 http://jsfiddle.net/ozu6c4eo/1/
<div id="d1">
<div id="d2"></div>
</div>
<style type="text/css">
*
{
margin:0;padding:0;
}
div#d1
{
width: 90vw;
height: 50.625vw;
background: pink;
max-height: 90vh;
max-width: 177.78vh;
margin: auto;
position: absolute;
top:0;bottom:0;
left:0;right:0;
}
div#d2
{
background: blue;
width:10%;
top: 0;
bottom: 0;
left: 10%;
position:relative;
margin:auto;
}
#d2:before{
content: "";
display: inline-block;
padding-top: 100%; /* initial ratio of 1:1*/
}
</style>
【问题讨论】:
标签: css