Align source text to top of another element (CSS)

I'm sure someone has done this before, but I cannot find a good enough search query to find anything about this.

I would like to align the baseline (and not the bottom of the text element, the baseline of the text itself) to the top of another div. It also means that I would like descenders to intersect with another div below it.

HTML looks something like this:

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

So I want .text have a baseline directly on top of the .box edge, and I want descenders (like "g") to intersect in .box . I tried to use the vertical-align property in CSS, but it did not work. I have a feeling that I need. Any ideas? Thanks!

Look at this image, the gray square will be .box , and the text part will be .text . Note that the descenders descend into the field, and the baseline has full contact with the box.

+5
source share
3 answers

How is it 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 is not determined, say, by the height of the capital letter T - it also includes ascents and descenders.

It is not possible to make CSS aware of the amount of space occupied by the ascending and descending mechanisms. Pushing pixel pixels is the best choice.

If you are worried that this is stored on different screens, and also for zooming in and out, this should be good: browsers very well maintain the proportions between the dimensions.

However, the only way to be 100% sure is to use an image or SVG.

+4
source

Try the following:

 <!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> 
+1
source

The way I was able to accomplish what your image displays is to use a negative margin in the bottom box.

 *{ margin: 0; } .text{ background: lightgrey; font-size: 24px; } .box{ background-color: tomato; width: 100%; height: 40px; margin-top: -12px; } 

Codepen

+1
source

Source: https://habr.com/ru/post/1239855/


All Articles