基于父元素高度的CSS实现1:1(正方形)宽高比。

5

我正在尝试制作一个类似日历的展示,其中日期框是正方形的,但整个日历本身不能滚动。

它应该像这样:

----------------------------------
|         header element         |
|--------------------------------|
|     additional element         |
|--------------------------------|
|       -----------------        | --> start calendar (.box_fit-container)
|       |sun|mon|tue|wed|        |
|       -----------------        |
|       |d1 |d2 |d3 |d4 |        |
|       |d1 |d2 |d3 |d4 |        |
|       |d1 |d2 |d3 |d4 |        | --> bottom of screen/viewport 
|       |d1 |d2 |d3 |d4 |        |     where it usually starts scrolling
|       |d1 |d2 |d3 |d4 |        |
|       -----------------        |
----------------------------------

我使用了 flex 来创建外部的“框架”,使得外部容器填充原始视口的剩余高度,同时感谢不同的 SO 贡献者,我也可以创建一个单独的正方形形状。但出于某种原因,我无法创建一个正方形,其中对象的宽度遵循其父元素的高度。

以下是我目前拥有的代码:

.box_fit-container {
  display: flex;
  flex-direction: column;
  height: 80vh; /* this was supposed to be 100% according to the SO source I found, but since I'm working on a legacy code and there are other elements above this new one so I changed into 80vh to fit as close as possible */
}
.box_fit-header {
  flex: 0 1 auto;
}
.box_fit-content {
  flex: 1 1 auto;
}
.square-box {
  position: relative;
  width: 100%;
  padding-top: 100%;
}
<div class="container">
  <div class="box_fit-container">
    <div class="box_fit-header">
      <div>some header content
    </div>
    <div class="box_fit-content">
      <!-- 
      I need this .square-box elem to be square-shaped 
      but doesn't overflow outside the .box_fit-content 
      -->
      <div class="square-box"></div>
    </div>
  </div>
</div>

1个回答

2
如果您可以确定标题的高度或者它始终固定,那么您可以考虑将max-width设置为80vh-标题高度。"原始答案"

.box_fit-container {
  display: flex;
  flex-direction: column;
  height: 80vh; /* this was supposed to be 100% according to the SO source I found, but since I'm working on a legacy code and there are other elements above this new one so I changed into 80vh to fit as close as possible */
  border:1px solid;
}
.box_fit-header {
  flex: 0 1 auto;
  border:1px solid red;
}
.box_fit-content {
  flex: 1 1 auto;
  border:1px green;
}
.square-box {
  position: relative;
  width: 100%;
  margin:auto;
  max-width:calc(80vh - 25px);
  border:2px solid;
}
.square-box:before {
  content:"";
  display:inline-block;
  padding-top: 100%;
}

* {
 box-sizing:border-box;
}
<div class="container">
  <div class="box_fit-container">
    <div class="box_fit-header">
      <div>some header content
    </div>
    <div class="box_fit-content">
      <!-- 
      I need this .square-box elem to be square-shaped 
      but doesn't overflow outside the .box_fit-content 
      -->
      <div class="square-box"></div>
    </div>
  </div>
</div>


很遗憾,不行。它还需要响应式设计。因此,如果我使用calc(80vh - [someheight]px),那么结果将会不同。 - dapidmini
哦,我误读了max-width部分...让我先试一下...谢谢。 - dapidmini
谢谢,它运行得很好,但现在又出现了另一个问题...我会在新的问题中发布它。谢谢。 - dapidmini

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接