Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Baseline of vertically stacked elements

I have a container of vertically stacked elements.

<div>
  <div>line 1</div>
  <div>line 2</div>
  <div>line 3</div>
  <div>line 4</div>
</div>

I want the baseline of the container to be identical to the baseline of a specific one of its elements, let's say the third one. It should look like this:

enter image description here

How can I do this with CSS?

As a related question, how is the baseline of such container of vertically stacked elements usually defined?

I want to give this container a property display: inline-block. This container appears next to other elements on a line, and I want them to be aligned according to the baseline.

like image 456
sawa Avatar asked Dec 27 '15 17:12

sawa


1 Answers

This makes the baseline of the container coincide with the baseline of the third child div.

.container > div:nth-of-type(3) ~ div {
  float: left;
  clear: both;
}

Examples:

.container {
  display: inline-block;
  background: yellow;
  padding: 0 0.5em;
  width: 8em;
}

.b1 > div:nth-of-type(1) ~ div {
  float: left;
  clear: both;
}

.b2 > div:nth-of-type(2) ~ div {
  float: left;
  clear: both;
}

.b3 > div:nth-of-type(3) ~ div {
  float: left;
  clear: both;
}

.b4 > div:nth-of-type(4) ~ div {
  float: left;
  clear: both;
}

.container > div:nth-of-type(1) {
  font-size: 14px;
}

.container > div:nth-of-type(2) {
  font-size: 16px;
}

.container > div:nth-of-type(3) {
  font-size: 24px;
}

.container > div:nth-of-type(4) {
  font-size: 20px;
}
<div class="container b1">
  <div>baseline</div>
  <div>line 2</div>
  <div>line 3</div>
  <div>line 4</div>
</div>
<div class="container">
  Lorem ipsum dolor sit amet
</div>
<div class="container">
  consectetur adipiscing elit, sed do eiusmod tempor incididunt
</div>
<hr>
<div class="container b2">
  <div>line 1</div>
  <div>baseline</div>
  <div>line 3</div>
  <div>line 4</div>
</div>
<div class="container">
  Lorem ipsum dolor sit amet
</div>
<div class="container">
  consectetur adipiscing elit, sed do eiusmod tempor incididunt
</div>
<hr>
<div class="container b3">
  <div>line 1</div>
  <div>line 2</div>
  <div>baseline</div>
  <div>line 4</div>
</div>
<div class="container">
  Lorem ipsum dolor sit amet
</div>
<div class="container">
  consectetur adipiscing elit, sed do eiusmod tempor incididunt
</div>

<hr>
<div class="container b4">
  <div>line 1</div>
  <div>line 2</div>
  <div>line 3</div>
  <div>baseline</div>
</div>
<div class="container">
  Lorem ipsum dolor sit amet
</div>
<div class="container">
  consectetur adipiscing elit, sed do eiusmod tempor incididunt
</div>
like image 83
Rick Hitchcock Avatar answered Oct 13 '22 06:10

Rick Hitchcock