CSS在使用纵横比时忽略子元素的宽度

7xzttuei  于 2023-04-08  发布在  其他
关注(0)|答案(1)|浏览(102)

我遇到了一个关于CSS的aspect-ratio的问题。
我一直在尝试将元素的宽度和高度(两者相同)设置为与父容器的高度相等。
在使用aspect-ratio时,父容器似乎忽略了子容器调整后的宽度,这意味着父容器的宽度错误。
我已经包含了一个codepen来说明这个问题。注意宽度是如何随着每个新元素的增加而增加的,但是宽度的增加并不对应于所添加元素的实际宽度。

* {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
}
body {
  padding: 8px;
}
.container {
  border: 1px solid red;
  display: flex;
  flex-direction: row;
  align-items: stretch;
  column-gap: 16px;
  
  width: fit-content;
}
.button_container {
  display: flex;
  column-gap: 8px;
  border: 1px solid green;
  width: fit-content;
}
.button {
  display: flex;
  align-items: center;
  justify-content: center;

  border: 1px solid black;
}
.first_case {
  height: 100%;
  aspect-ratio: 1 / 1;
}
.second_case {
  height: 100%;
  width: 56px;
}
<p>Fixed width (this is how it should look)</p>
<div class="container">
  <div>
    Text<br/>More text<br/>Lots of text
  </div>
  <div class="button_container">
    <div class="button second_case">
      A
    </div>
    <div class="button second_case">
      B
    </div>
  </div>
</div>

<p>Aspect ratio</p>
<div class="container">
  <div>
    Text<br/>More text<br/>Lots of text
  </div>
  <div class="button_container">
    <div class="button first_case">
      A
    </div>
    <div class="button first_case">
      B
    </div>
  </div>
</div>

https://codepen.io/th3o4or/pen/ZEoqMrm

xjreopfe

xjreopfe1#

你可以使用“display:flex;“为容器和设置一些尝试一些不同的与和高度值。其解决:https://codepen.io/sawacrow/pen/eYPYjwr

* {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
}
body {
  padding: 8px;
}
.container {
  border: 1px solid red;
  display: flex;
  flex-direction: row;
  align-items: stretch;
  column-gap: 16px;
}
.button_container {
  display: flex;
  flex-direction: row;      width: -webkit-fill-available;
  column-gap: 8px;
  border: 1px solid green;
}
.button {
  display: flex;
  align-items: center;
  justify-content: center;

  border: 1px solid black;
}
.first_case {
  height: 100%;
  aspect-ratio: 1 / 1;
}
.second_case {
  height: 100%;
  width: 56px;
}
<p>Fixed width (this is how it should look)</p>
<div class="container">
  <div>
    Text<br/>More text<br/>Lots of text
  </div>
  <div class="button_container">
    <div class="button second_case">
      A
    </div>
    <div class="button second_case">
      B
    </div>
  </div>
</div>

<p>Aspect ratio</p>
<div class="container">
  <div>
    Text<br/>More text<br/>Lots of text
  </div>
  <div class="button_container">
    <div class="button first_case">
      A
    </div>
    <div class="button first_case">
      B
    </div>
  </div>
</div>

相关问题