CSS-使项目在上一行的中间开始

时间:2018-10-17 12:49:50

标签: 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

如您在图片上看到的那样,在某些情况下,字幕可能比标题长,有时没有。

我尝试了不同的方法,但是我无法弄清楚。这是我最后的尝试。这里的问题是,(当然)随着字幕越长,“标题” 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>

1 个答案:

答案 0 :(得分:1)

这里是一个想法,您可以创建一个隐藏的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>