CSS - 使元素从上一行的中间开始

标签 css grid-layout css-grid

我正在尝试使用 CSS Grid 来创建一个从上一行中的 div 中间开始的 div。我希望两个 div 都环绕文本。这就是我要实现的目标:

Aim : the div on the second row starts in the middle of the first div

正如您在图片上看到的,在某些情况下,副标题可能比标题长,有时则不会。

我尝试了不同的方法,但我无法弄清楚。这是我最后一次尝试。这里的问题是(当然)随着副标题的变长,“Title”div 变宽。

#container{
  border:solid black;
  display:grid;
  grid-template-columns: max-content auto;
  grid-template-rows:1fr 1fr;
}

#title{
  border:solid blue;
  grid-column:1/2;
  grid-row:1/2;
}

#subtitle-container{
  border:solid red;
  grid-column:1/2;
  grid-row:2/3;
  
  display:grid;
  grid-template-columns:50% max-content;
}

#subtitle-text{
  border:solid green;
  grid-column:2/3;
}
<div id="container">
  <div id="title">Title</div>
  <div id="subtitle-container">
    <div id="subtitle-text">This is a rather long subtitle
    </div>
  </div>
</div>

最佳答案

这是一个想法,您可以在其中创建一个隐藏的 float 元素来推送字幕。您只需将 float 元素设置为标题宽度的 50%,并且您需要将标题的宽度设置为 fit-content。 .

.container{
  border:solid black;
  margin:5px;
}

.title{
  border-bottom:solid blue;
  width:-moz-fit-content;
  width: fit-content;
}

.title:after {
  content:"";
  float:left;
  width:50%;
  height:2px; /*not needed*/
  background: red; /*not needed*/
  margin-top:10px; /*need to be a small value*/
}
.subtitle-text{
  border:solid green;
  display:inline-block;
}
<div class="container">
  <div class="title">Title</div>
  <div class="subtitle-text">This is a rather long subtitle</div>
</div>

<div class="container">
  <div class="title">Long long Title</div>
  <div class="subtitle-text">Subtitle</div>
</div>

<div class="container">
  <div class="title">Very Long long Title</div>
  <div class="subtitle-text">Subtitle</div>
</div>

关于CSS - 使元素从上一行的中间开始,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52855280/

相关文章:

css - 网格元素 100% 父级高度

CSS - <p> 滑动时留下痕迹

android - 修复了在移动屏幕中滚动时 div 下降的问题 - html/css

html - Bootstrap 网格在 bootply 中正常工作但在 html 中不正常,为什么?

java - 如何更改网格中的按钮标签?

css - Chrome 瘦身 CSS 网格神秘缺口

html - 在不向父级提供高度的情况下在 flex 列中排列元素

html - 样式表链接 rel 和快捷图标链接 rel 不能共存

css - 动画只影响 css-doodle 的第一个元素

html - 响应式地制作图像网格中心