【问题标题】:Padding trick aspect ratio element - Vertical centering填充技巧纵横比元素 - 垂直居中
【发布时间】:2015-04-30 03:14:08
【问题描述】:

我正在尝试垂直居中使用 padding-bottom 创建所需纵横比的元素(对于视频)。我希望有顶部和底部的黑色边框,就像电影以比拍摄时更高的纵横比显示时一样:

body{
    padding:0;
    margin:0;
    position:relative;
    display:block;
}
main{
    background: url(http://placekitten.com/1280) no-repeat center center;
    background-size: cover;
    width:100%;
    padding-top:56.25%;
    width:100%;
}

http://jsfiddle.net/y4tcufo5/ - 测试用例

我已经尝试过 top:50% ;变换:translateY(-50%) ;元素上的技巧,但似乎没有任何效果!我知道这与使用填充而不是宽度和高度有关,但我似乎无法以任何其他方式将元素装配到设计中。

有没有可能解决这个问题:

  • 使用填充技巧和另一种垂直居中元素的方式
  • 放弃填充并通过其他方式实现纵横比
  • 使用弹性框什么的

非常感谢任何帮助!

【问题讨论】:

    标签: html css web flexbox


    【解决方案1】:

    用这四行代码将任何东西垂​​直居中

    position: relative;
    top: 50%;
    transform: translateY(-50%);
    max-height: 100%;
    

    将此应用于要垂直居中的元素的包装器

    (Demo)

    HTML

    <div class="wrap">
        <main></main>
    </div>
    

    CSS

    html, body {
        padding:0;
        margin:0;
        height: 100%;
    }
    main{
        background: url(http://placekitten.com/1280) no-repeat center center;
        background-size: cover;
        width:100%;
        padding-top:56.25%;
    }
    .wrap {
        position: relative;
        top: 50%;
        transform: translateY(-50%);
        max-height: 100%;
    }
    

    【讨论】:

    • 谢谢,这正是我所需要的!我是如此接近!
    猜你喜欢
    • 2011-05-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-07
    • 2020-07-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多