Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Align baseline of text to the top of another element (CSS)

Tags:

html

css

I'm sure someone's done this before, but I can't come up with a good enough search query to find anything about it.

I'd like to align the baseline (not the bottom of the text element, the baseline of the text itself) to the top of another div. This also means I'd like the descenders to intersect with the other div below it.

HTML looks something like this:

<div id="text">text</div>
<div id="box"></div>

So I want .text to have its baseline directly on top of the top edge of .box, and I want the descenders (like "g") to intersect into .box. I was trying to use the vertical-align property in CSS but it wasn't working. I have a feeling that's what I need though. Any ideas? Thanks!

See this image, the gray box would be .box and the text part is .text. Notice the descenders going down into the box and the baseline having full contact with the box.

like image 513
Zach Avatar asked Jan 05 '16 04:01

Zach


People also ask

How do I align text to the top in HTML?

To place an item at the top or bottom of its cell, insert the "VALIGN=" attribute within the code for that cell. To vertically align an entire row (e.g., placing all data in that row at the tops of the cells), insert the "VALIGN=" attribute within the code for that row.

How do you position an element on top of another?

You can use the CSS position property in combination with the z-index property to overlay an individual div over another div element. The z-index property determines the stacking order for positioned elements (i.e. elements whose position value is one of absolute , fixed , or relative ).


2 Answers

Like this, using line-height?

#box{
  display:block;
  width:100%;
  height:200px;
  background-color:#ccc;
}
#text{
  text-align:center;
  font-size:48px;
  line-height:30px;
}
<div id="text">TEXT<em>pgjiq</em></div>
<div id="box"></div>

The difficulty is that the height of the font isn't determined by, say, the height of the capital letter T -- it also includes the ascenders and descenders.

There's no way to make CSS cognizant of the amount of space taken up by the ascenders and descenders. Nudging it pixel-by-pixel is your best bet.

If you're worried about this being preserved on different screens and on zooming in and out, it should be fine: browsers are very good at preserving the proportions among dimensions.

That said, the only way to be 100% certain is to use an image or an SVG.

like image 115
RobertAKARobin Avatar answered Sep 23 '22 03:09

RobertAKARobin


Try this:

<!DOCTYPE html>
<html>
<head>
    <style>
        * {font-family: tahoma; font-size: 14px;}
        #text {margin-bottom: -3px;}
        #box {background-color: #ddd; width: 100%; height: 100px;}
    </style>
</head>

<body>
<div id="text">TEXT gjipq</div>
<div id="box"></div>
</body>
</html>
like image 21
S.Yavari Avatar answered Sep 25 '22 03:09

S.Yavari