【问题标题】:problem with width: fit-content when there's span inside宽度问题:内部有跨度时适合内容
【发布时间】:2022-09-23 07:24:10
【问题描述】:

如何使 div 的宽度取决于该 div 内的 span 宽度? fit-content 无法正常工作。

我有这个 html 代码:

<div class=\"bubble\">this text is long enouuuugh<span class=\"inside\">content to fit inside box</span></div>
<div class=\"bubble\">this isn\'t<span class=\"inside\">content to fit inside box</span></div>
<!-- how I want it to look, but not using style=\"width:110px\" -->
<div class=\"bubble\" style=\"width:110px\">ok<span class=\"inside\">content to fit inside box</span></div>

和CSS:

.bubble {
    float: right;
    clear: right;
    width: fit-content;
    margin: 19px auto;
    border: 2px solid red;
    padding: 10px;
    padding-bottom: 20px;
}
.inside
{
  position: absolute;
  display: block;
  width: fit-content;
  right: 0;
  margin-top: 1px;
  margin-right: 12px;
  font-size: 12px;
  font-weight: 500;
  color: blue;
  background: white;
}

我希望它看起来像第三个框,但不是宽度:xx px,因为黑色文本和蓝色文本的长度因框而异,并非每次都相等。

  • 你为什么使用位置;绝对?这就是问题所在

标签: html css


【解决方案1】:

尝试以下操作:

.bubble {
  float: right;
  clear: right;
  width: fit-content;
  margin: 19px auto;
  border: 2px solid red;
  padding: 10px;
  padding-bottom: 20px;
}

.inside {
  display: block;
  width: fit-content;
  right: 0;
  margin-top: 1px;
  margin-right: 12px;
  font-size: 12px;
  font-weight: 500;
  color: blue;
  background: white;
}
<body>

  <div class="bubble">this text is long enouuuugh<span class="inside">content to fit inside box</span></div>
  <div class="bubble">this isn't<span class="inside">content to fit inside box</span></div>
  <!-- how I want it to look, but not using style="width:110px" -->
  <div class="bubble" style="width:110px">ok<span class="inside">content to fit inside box</span></div>
</body>

【讨论】:

    【解决方案2】:

    只需删除position: absolute,您就会得到您想要的结果。这里有一些关于 position 属性如何工作的阅读材料 https://developer.mozilla.org/en-US/docs/Web/CSS/position

    【讨论】:

      猜你喜欢
      • 2015-03-03
      • 2017-08-08
      • 1970-01-01
      • 2014-01-14
      • 2014-05-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多