html - CSS "width: auto"不适用于 <div>

标签 html css

我希望 .test_info 的宽度为 auto,与 #test 的宽度不同。

https://jsfiddle.net/ef6ukobf/

#test {
  background: #26A65B;
  height: 30px;
  width: auto;
  margin-top: -8px;
  margin-left: -8px;
  margin-right: -8px;
}
.test_info {
  background: #00ff00;
  border-radius: 5px;
  height: 20px;
  width: auto;
  margin-top: -2px;
  margin-left: 20px;
}
<div id="test">
  <div class="test_info">50</div>
</div>

最佳答案

<div>元素是 block 级别的,默认情况下它占据容器的整个可用宽度。

如果你希望它是自动宽度(取决于里面的内容),你可以这样做:

.test_info {
  display: inline-block; /*or table*/
}

#test {
  background: #26A65B;
}
.test_info {
  background: #00ff00;
  display: inline-block;
}
<div id="test">
  <div class="test_info">50</div>
</div>

关于html - CSS "width: auto"不适用于 <div>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38251555/

相关文章:

javascript - 对齐 self :flex start is not sending child element to the top

html - 如何使用固定顶部解决错误设置侧边栏

javascript - 如何独立滚动 2 个不同的面板?

HTML/CSS : 100% container with background image - clickable link should be positioned on image?

javascript - CSS,高度为 :auto, 的图像在屏幕调整大小时覆盖其下方的 div(手机水平放置)

css - 加载带有大图像的 DIV 会延迟页面其余部分的加载

html - 回退到 element.style 媒体查询?

asp.net - javascript 和 css 文件的安全警告?

javascript - 如何通过 HTTP 将 HTML 文件加载到字符串中以便在 JavaScript 中使用?

css - BlueprintJS 未加载其图标 CSS 模块,但能够加载核心 CSS 模块