【问题标题】:Maintain aspect ratio and position relative to parent保持纵横比和相对于父级的位置
【发布时间】: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>

#d2position 更改为相对使其成为所需的大小和纵横比,但位于其父级的顶部和中心的右侧。 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


【解决方案1】:

演示 - http://jsfiddle.net/victor_007/6tvsmLnp/1/

div#d2 {
    background: blue;
    width: 10%;
    top: 50%; /** changed to center vertically **/
    bottom: 0;
    left: 10%;
    position: relative;
    transform: translateY(-50%); /** added to center vertically **/
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-03-16
    • 2018-10-21
    • 2017-11-16
    • 2017-04-04
    • 1970-01-01
    • 2012-08-25
    • 2013-03-04
    • 2012-12-16
    相关资源
    最近更新 更多