html - CSS:根据文本宽度显示内联或 block - 无 javascript

标签 html css

所以我有以下 DOM

  <div class="parent">
    <div class="first-child">Some Text</div>
    <div class="second-child">Some other text that can sometimes be very long, sometimes short</div>
  </div>

如果 .second-child 小于 ,我希望 display: inline.first-child 500 像素。我想要它 display: block 否则。

我正在寻找一个纯 CSS 解决方案,没有 javascript。

最佳答案

你可以使用 flexbox 来模拟​​这样的行为:

.parent {
  display:flex;
  flex-wrap:wrap;
  margin-bottom:20px;
}
.first-child {
  border:1px solid green;
  flex-basis:calc(100% - 500px); /*This will make the element to wrap when the second one is bigger than 500px*/
}
.second-child {
   border:1px solid red;
}

* {
  box-sizing:border-box;
}
<div class="parent">
    <div class="first-child">Some Text</div>
    <div class="second-child">shot text (less than 500px)</div>
  </div>

  <div class="parent">
    <div class="first-child">Some Text</div>
    <div class="second-child">medium text but still shorter to not wrap (less than 500px)</div>
  </div>

  <div class="parent">
    <div class="first-child">Some Text</div>
    <div class="second-child">very long text  Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam tincidunt sagittis orci nec accumsan. Phasellus quis dui eu dolor pellentesqu (bigger than 500px)</div>
  </div>

关于html - CSS:根据文本宽度显示内联或 block - 无 javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51170202/

相关文章:

CSS 未在某些子域上加载?

html - 我可以使用字形作为可折叠的要点吗?

php - 每行上回显的删除按钮

javascript - 如何从 div 内的视频元素获取源并将其传递给另一个视频元素 - javascript

javascript - td 没有父表标签

javascript - 单击按钮时显示/阻止消息

javascript - 如何清除setInterval的fillText?

javascript - 更改值时 Vue v-show 不呈现

objective-c - 如何将 css 应用于 native ios 应用程序?

JavaScript 通过滚动添加一次类