Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Align span to top of its container

Tags:

css

It seems that when line-height is larger than 1.1 times font-size, the text gets vertically centered in the line. Can it be vertically aligned instead?

In this example

p {
  background-color: pink;
  font-size: 20px;
  line-height: 40px
}

span {
  background-color: lightblue;
}
<p>
  <span>Hello World</span> Hello World Hello World Hello World Hello World Hello World Hello World Hello World Hello World
</p>

I want the text to butt up against the top of the pink box. All the extra pink space would be below the blue, instead of split above and below each line. The blue box would butt up against the top of the pink. I haven’t found vertical-align: top or adding line-height to the span to help.

(Edited to show that the text can be very long.)

like image 891
JPM Avatar asked Jun 15 '17 02:06

JPM


2 Answers

Different from Daniel's answer but I guess this meets your requirements too?

p {
  background-color: pink;
  font-size: 20px;
  vertical-align: top;
  height: 40px;
}

span {
  background-color: lightblue;
}
<p>
  <span>Hello World</span> Hello World
</p>

Well, if your text is multiline, I could only think of this solution:

$("#fontsize-input").on("input",() => {
  $("p").css("font-size",$("#fontsize-input").val()+"px");
});
p {
  background-color: pink;
  font-size: 25px;
  line-height: 2em;
}

span {
  position: relative;
  top: calc(-0.45em + 1px);
}

.highlight {
  background-color: lightblue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="range" min="10" max="40" id="fontsize-input"/>
<p>
  <span class="highlight">Hello World</span> <span>Hello World Hello World Hello World Hello World Hello World Hello World Hello World Hello World</span>
</p>
like image 67
Richard Yan Avatar answered Sep 19 '22 21:09

Richard Yan


In order to keep the line-height, you can add display: inline-block; to the span element.

p {
  background-color: pink;
  font-size: 20px;
  line-height: 40px
}

span {
  background-color: lightblue;
  display: inline-block;
}
<p>
  <span>Hello World</span> Hello World Hello World Hello World Hello World Hello World Hello World Hello World Hello World
</p>
like image 21
j-printemps Avatar answered Sep 19 '22 21:09

j-printemps