【问题标题】:2 elements inside 1 div, i want the other element to scale with the first one1个div内的2个元素,我希望另一个元素与第一个元素一起缩放
【发布时间】:2021-09-03 08:41:13
【问题描述】:

我有一个按钮组件,在按钮的左侧带有一点重音样式。我希望按钮根据内容获得高度。 “文本”变量可以是任何文本,因此它可以随时更改。我希望按钮重音与文本一起缩放,但我不能使用 100% 或类似的东西,因为它的父级没有任何设置高度(因为我希望它适合内容)。 button_accent 在我手动设置时确实会得到高度,但我希望它是动态的

  <div className={`${buttonStyles.button}`} >
    <div className={`${buttonStyles.button_accent} h-full`}></div>
    <div className="mr-3 ml-3 justify-start w-full flex items-center">
      {text}
    </div>
  </div>

Button.module.css:

.button {
  display: flex;
  height: auto;
  min-height: 80px;
  border: 1px solid #d8fc9133;
  font-size: 24px;
  color: white;
  font-weight: medium;
  background: rgb(128, 128, 128, 0.5);
  align-items: center;
}
.button:hover {
  background: rgb(128, 128, 128, 1);
  cursor: pointer;
}
.button_accent {
  width: 12.77px;
  background-color: #d8fc91;
}

这里是高度设置为 65 像素的重音按钮。 (没有设置高度,重音高度为0)

【问题讨论】:

    标签: html css next.js tailwind-css


    【解决方案1】:

    您可以将position: relative 添加到父容器.button,然后绝对定位第一个div .button_accent 相对于父容器。这样您就不需要为.button_accentheight 值设置任何明确的absolute length unit,但现在可以使用height: 100% 并让重音容器增长或“缩放”以匹配其父级的高度。

    如果您删除文本内容,您将看到重音仍然显示并缩放以填充其父级,该父级的高度与您的min-height: 80px 声明相比必须至少为 80 像素。当你去掉这个显式的min-height 并且&lt;td&gt; 中没有文本内容时,重音符号将不会显示,因为父内容框是空的,高度为零。

    定位元素后,我们可以使用height: 100% 或其他相对长度单位来使重音与文本一起缩放,因为它相对于父容器绝对定位,该父容器是一个弹性盒,具有auto 高度和@987654334 @ 的 80 像素。如果您不希望重音占据父容器高度的 100%,但要在包含的图像中显示一些顶部/底部空间,只需使用 height: 80% 或一些 relative length unit 将重音调整为您喜欢的大小.

    .button {
      position: relative;
      display: flex;
      height: auto;
      min-height: 80px;
      border: 1px solid #d8fc9133;
      font-size: 24px;
      color: white;
      font-weight: medium;
      background: rgb(128, 128, 128, 0.5);
      align-items: center;
    }
    .button:hover {
      background: rgb(128, 128, 128, 1);
      cursor: pointer;
    }
    
    .button div:last-child {
      margin: 0 1.5rem;
    }
    
    .button_accent {
      position: absolute;
      left: 0;
      width: 12.77px;
      height: 80%; /* 100% fills entire height of parent */
      background-color: #d8fc91;
    }
    <div class="button">
        <div class="button_accent"></div>
        <div class="mr-3 ml-3 justify-start w-full flex items-center">
          Some text
        </div>
      </div>

    【讨论】:

    • @KimVu 这有助于回答您的问题吗?
    • 是的,这很好用!谢谢你:)
    猜你喜欢
    • 2022-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-07
    • 1970-01-01
    • 2020-10-05
    • 2022-01-25
    相关资源
    最近更新 更多