Marie D.
Marie D.

Reputation: 201

CSS - Make an item start in the middle of previous row

I'm trying to use CSS Grid to have a div that starts in the middle of the div in the row above. I want both divs to wrap around the text. This is what I'm trying to achieve:

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

As you see on the picture, in some cases, the subtitle might be longer than the title, and sometimes not.

I tried different ways but I can't figure it out. Here's my last attempt. The problem here is that (of course) the "Title" div becomes wider as the subtitle is longer.

#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>

Upvotes: 4

Views: 514

Answers (1)

Temani Afif
Temani Afif

Reputation: 272880

Here is an idea where you can create a hidden float element that will push the subtitle. You simply make the float element 50% width of the title and you need to make the width of the title 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>

Upvotes: 1

Related Questions