是否可以缩放容器以适合另一个容器?

时间:2018-08-10 06:11:44

标签: css3

在各种技术中,一遍又一遍的关键功能是获取任何内容并将其适合任何其他内容。这不是一个小问题,几年前,我得到了一个非常冗长的JS解决方案,对此我并不特别满意。

我已将问题简化为几个div。 inner容器包含一个topbottom容器,现在我想将inner放入另一个outer容器中,使其完全保持宽高比和居中。

这样的事情。

demo

基本模板。这里的问题之一是,从CSS角度来看,我不确定职责。我看到的类似于object-fit: contain,唯一的区别是我有一个div容器而不是一个几何对象,但是却寻求类似的行为。

html, body {
  width: 100%;
  height: 100%;
  margin: 0
}

.outer {
  width: 100%;
  height: 100%;
}

.inner {
  
}

.top {
  background-color: #0ff;
  width: 1000px;
  height: 1000px;
}

.bottom {
  background-color: #0f0;
  width: 1000px;
  height: 1000px;
}
<div class=outer>
  <div class=inner>
    <div class=top>
    </div>
    <div class=bottom>
    </div>
  </div>
</div>

Here is the same Fiddle

修改

只是要明确指出不应有滚动条。 inner可以是任何大小。它可能有1000个YouTube嵌入内容,或一个2000x2000的画布游戏。但是,如果outer是100px x 100px,则所有内容都“适合”该空间。

修改

基本上我想要object-fit: contain。里面有divimg时。 contain将缩放以使该几何形状适合父容器。不会裁剪或调整大小。但是,我有content div而不是图像。那么,一个人如何重新创建相同的行为?

2 个答案:

答案 0 :(得分:0)

解决方案1:移动响应

.outer{
  max-width:100%;
}

.inner{
  border:1px solid red;
  max-width:100%;
}

/*You can join both selectors in CSS with same properties */
.top,.bottom {
  box-sizing:border-box;
  -moz-box-sizing: border-box; 
  border:4px solid blue;
  width: 1000px;
  height:1000px;
  max-width:100%;

  /*The max-width will make the boxes fit inside the screen (no scrolling for the width so no need to use overflow-x), but the divs will not be 1000px in case the containing div or in case the borwser window is less than 1000px*/
}

Demo in JsFiddle

解决方案2: / *具有固定大小的简单数学* /

.inner{
   border:1px solid red;
   width:1000px;
   height: 2000px;
}
.top, .bottom{     
  box-sizing:border-box;
  -moz-box-sizing: border-box; 
   border:4px solid blue;
   width: 1000px;
   height: 1000px;
}

Demo in JsFiddle

解决方案3: / 使用高度:50%;因为您想除以一半,但是如果您想保持1000px的高度, 在某些情况下,您可能需要min-height:1000px;以防止将高度调整为小于1000像素; /

.inner{
   border:1px solid red;
   width:1000px;
   height: 2000px;
}
.top , .bottom{
   box-sizing:border-box;
   -moz-box-sizing: border-box; 
   border:4px solid blue;
   width: 1000px;
   height: 1000px;
   max-height:50%;
}

Demo in JsFiddle

注意事项: 当您要设置特定大小时,不需要为外部div使用width:100%和height:100%,除非您要使用移动响应设计,否则还需要max-width,因为使用百分比来制作div与浏览器窗口或div容器成比例。

最大宽度:100%;所有div(父母和孩子)都可以使用移动设备,因此在调整窗口大小以适合窗口时,将调整宽度, box-sizing:border-box; -moz-box-sizing:边框框;在向其添加填充和边框时,将.top,.bottom div包含在.inner div中。

答案 1 :(得分:0)

display: grid添加到.outer

看看这个片段:

https://jsfiddle.net/yxho9n5a/31/

相关问题