【问题标题】:Make square div fill parent at all time without losing its aspect ratio始终使方形 div 填充父级而不会丢失其纵横比
【发布时间】:2015-08-07 21:09:26
【问题描述】:

假设我有以下 HTML:

<div class="parent">
  <div class="square-child"></div>
</div>

我想要完成的是让square-child 尽可能多地填写其父项,而不会丢失属性,并始终保持居中。我做了一个草图,square-childbeing 显示为红色,parentbeing 显示为绿色。

我正在阅读以下 SO 问题,但无法使其居中:Maintain the aspect ratio of a div with CSS

编辑:添加小提琴https://jsfiddle.net/2bg1jzg3/2

【问题讨论】:

  • 您已经链接了正确答案;看起来当前的问题是如何使元素水平和垂直居中?
  • 当我遵循指南时,正方形会溢出父级,而不是缩小高度以适应父级。
  • 如果父级大小是相对于视口的,你可以在这里找到答案:Fit responsive square in viewport according to width and height 否则,你将需要 JS 来计算子级的大小。
  • 其他问题:你想在孩子身上展示什么样的内容?
  • 背景图片,见附上的小提琴。

标签: html css


【解决方案1】:

也许这样的事情会有所帮助: http://jsfiddle.net/2bg1jzg3/5/

$(".visual").animate({
    width: "600px",
    height: "300px"
}, 2000, function () {
    // Animation complete.
});
.visual {
    background-color:lightblue;
    position:absolute;
    overflow:hidden;
    width:250px;
    height:600px;
}
.parent {
    width:auto;
    height:100% !important;
    position: relative;
    display: block;
}
.parent .square-child {
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    background-repeat:no-repeat;
    background-size:cover;
    background-position: center;
    background-image: url('http://lorempixel.com/output/abstract-q-g-850-480-8.jpg');
    width: 50%;
    height: 0;
    padding-bottom: 50%;
    margin: auto;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="visual">
    <div class="parent">
        <div class="square-child"></div>
    </div>
</div>

【讨论】:

  • 酷,但正方形不适合,因为你定义它的宽度为 50% :(
  • 我猜长宽比和宽度可以用 javaScript 来完成,然后就可以了 :)
  • 确实如此。我想我必须使用JS。
【解决方案2】:

试试这个Fiddle.

<div class="parent">
  <div class="square-child"></div>
</div>

CSS

.parent{
    width: 100%;
    background: #f00;   
    height: 100px;
}
.square-child{
    width: 50%;
    margin: 0 auto;
    background: #00FF63;
    height: 100%;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-24
    • 2016-02-12
    • 2016-03-11
    • 2016-03-21
    • 2021-12-13
    • 2018-10-21
    相关资源
    最近更新 更多