防止弹性项目高度扩展以匹配其他弹性项目 [英] Prevent a flex items height from expanding to match other flex items

查看:20
本文介绍了防止弹性项目高度扩展以匹配其他弹性项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一个容器中有两个元素,它们通过使用 flex box 并排.在第二个元素 (.flexbox-2) 上,我在 CSS 中设置它的高度.但是,第一个元素 (.flexbox-1) 将匹配 .flexbox-2 的高度.我如何阻止 .flexbox-1 匹配 .flexbox-2 的高度,而只保留其自然高度?

这是我目前所拥有的(也可以作为 jsFiddle)

.container {显示:-webkit-flex;-webkit-flex-direction: 行;}.flexbox-1 {-webkit-flex: 1;边框:纯 3px 红色;}.flexbox-2 {-webkit-flex: 2;边框:纯 3px 蓝色;高度:200px;左边距:10px;}

<div class="flexbox-1">.flexbox-1</div><div class="flexbox-2">.flexbox-2</div>

解决方案

这是一个旧的解决方案.我的答案被这个 Aaron 使用 align-self 的新答案所取代.这是一个更好的解决方案,不依赖于 CSS 怪癖.

只要弹性容器本身没有高度,你就可以在第一个弹性项目上设置height: 0%.因为它没有从父级继承的高度,任何百分比高度都会导致它折叠.然后它会随着它的内容而增长.

示例

在这个例子中,我删除了 -webkit 前缀.只有 Safari 才真正需要,前缀可以添加上面非- 前缀版本.我还删除了 flex-direction: row 因为它是默认值.

.container {显示:弹性;}.flexbox-1 {弹性:1;高度:0%;边框:纯 3px 红色;}.flexbox-2 {弹性:2;边框:纯 3px 蓝色;高度:200px;左边距:10px;}

<div class="flexbox-1">.flexbox-1</div><div class="flexbox-2">.flexbox-2</div>

I have two elements inside a container, which are being side-by-side by using flex box. On the second element (.flexbox-2), I am setting it's height in the CSS. However, then the first element (.flexbox-1) will match the height of .flexbox-2. How would I stop .flexbox-1 from matching the height of .flexbox-2, and instead just retain its natural height?

Here is what I have so far (also available as a jsFiddle)

.container {
  display: -webkit-flex;
  -webkit-flex-direction: row;
}
.flexbox-1 {
  -webkit-flex: 1;
  border: solid 3px red;
}
.flexbox-2 {
  -webkit-flex: 2;
  border: solid 3px blue;
  height: 200px;
  margin-left: 10px;
}

<div class="container">
  <div class="flexbox-1">.flexbox-1</div>
  <div class="flexbox-2">.flexbox-2</div>
</div>

解决方案

This is an old solution. My answer is superseded by this new answer by Aaron using align-self. That is a better solution that does not rely on a CSS quirk.

As long as the flex container has no height itself, you can set height: 0% on the first flex item. Because it has no height to inherit from its parent, any percentage height will cause it to collapse. It will then grow with its contents.

Example

In this example I have removed the -webkit prefix. It's only really required for Safari and the prefix can be added above the non-prefixed version. I also removed flex-direction: row as it is the default value.

.container {
  display: flex;
}
.flexbox-1 {
  flex: 1;  
  height: 0%;  
  border: solid 3px red;
}
.flexbox-2 {
  flex: 2;
  border: solid 3px blue;
  height: 200px;
  margin-left: 10px;
}

<div class="container">
  <div class="flexbox-1">.flexbox-1</div>
  <div class="flexbox-2">.flexbox-2</div>
</div>

这篇关于防止弹性项目高度扩展以匹配其他弹性项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆