在不丢失宽高比的情况下,始终使方形div填充父级

时间:2015-05-26 09:15:28

标签: html css

假设我有以下HTML:

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

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

enter image description here

我正在阅读以下SO问题,但无法将其置于中心位置:Maintain the aspect ratio of a div with CSS

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

2 个答案:

答案 0 :(得分:1)

试试这个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%;
}

答案 1 :(得分:1)

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

&#13;
&#13;
$(".visual").animate({
    width: "600px",
    height: "300px"
}, 2000, function () {
    // Animation complete.
});
&#13;
.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;
}
&#13;
<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>
&#13;
&#13;
&#13;