Flex - 项目应仅占用与文本一样多的空间

问题描述 投票:0回答:1

我有一个弹性容器和 2 件物品。浅蓝色物品有多个跨度。我想要实现的是使浅蓝色项目的最大宽度与文本跨度一样大。弹性项目也应该与文本始终换行一样大。我提供了一个代码沙箱用于测试。屏幕截图显示,在特定视口宽度下,浅蓝色容器比文本大得多

.flex-container {
  display: flex;
  align-items: center;
  /* Align items vertically */
}

.flex-item {
  flex-shrink: 1;
  /* Allow items to shrink */
  padding: 10px;
  margin: 5px;
  display: inline-flex;
  align-items: center;
  /* Center items vertically */
}

.light-blue {
  background-color: #d9edf7;
  /* Light blue background */
  border-radius: 10px;
  /* Rounded corners */
  display: inline-flex;
  /* Align children horizontally */
  white-space: normal;
  /* Allow text to wrap */
}

.blue {
  background-color: #337ab7;
  /* Blue background */
  border-radius: 10px;
  /* Rounded corners */
  color: white;
  /* White text */
  padding: 10px 20px;
  text-align: center;
}


/* Optional styling for icon */

.icon {
  margin-right: 5px;
}
<div class="flex-container">
  <div class="flex-item light-blue">
    <span class="icon">📅</span>
    <span class="text">Termine sind frei verfügbar</span>
  </div>
  <div class="flex-item blue">
    Termine anzeigen
  </div>
</div>

Light blue div width too wide

javascript html css
1个回答
0
投票

首先删除所有您不需要的规则。 Flex 项目不需要

display: inline-flex;
(你几乎从不需要 inline-flex),也不需要 white-space: normal;
 (这是默认值),并且你的颜色类应该只设置颜色、边框半径等在 .flex-item 类上。

完成所有这些,我们会自动获得正确的行为:

.flex-container { display: flex; align-items: center; .flex-item { flex-shrink: 1; padding: 10px; margin: 5px; border-radius: 10px; .icon { margin-right: 5px; } /* "fake" a span that's too small */ span.text { display: inline-block; width: 6em; vertical-align: middle; } } } .light-blue { background-color: #d9edf7; } .blue { background-color: #337ab7; color: white; }
<div class="flex-container">
  <div class="flex-item light-blue">
    <span class="icon">📅</span>
    <span class="text">Termine sind frei verfügbar</span>
  </div>
  <div class="flex-item blue">
    Termine anzeigen
  </div>
</div>

© www.soinside.com 2019 - 2024. All rights reserved.