-2

This is my problem in short: https://jsfiddle.net/b6wLwkfs/

Long story: I have a div with some text in it. It initially creates some space on top and bottom of my div (this is not padding). I would like my div to only cover the text and not create extra space. This is my only css:

div {
  background-color: black;
  color: white;
  font-size: 50px
}

<div>This is the text</div>

What I am looking for is to narrow down the div to only contains the text without creating any space on top of bottom. I acknowledge that if you tweaking a bit with px, you will achieve that but I am looking for more generic approach since font size will be different by cases.

Tri Nguyen
  • 21
  • 7

2 Answers2

2

Your code below is missing a (;) after font-size: 50px; now to achieve the space reduction I suggest you use line-height with the same font-size refer to my correction

Your Code

div {
  background-color: black;
  color: white;
  font-size: 50px
}

My Correction

div {
  background-color: black;
  color: white;
  font-size: 50px;
  line-height: 50px;
}
Hassan Sani
  • 124
  • 2
  • 9
  • 1. The final semi-colon is a good practice, but it's not a must. 2. The line-height actually make the div get smaller in height, but doesn't eliminate the space on top and bottom – Tri Nguyen Apr 29 '17 at 14:23
0

There is likely no 'generic' way to do this, as that spacing you're seeing is actually part of the font face, and whatever adjustments you make to solve the 'problem' for this font, will not necessarily work on other fonts.

For example, just take a look at how Arial displays, as it's different than the default font that is used without setting a specific font-family, and as such a fix for the default font would likely have to be adjusted for Arial.

p {
  background-color: black;
  color: white;
  font-size: 50px;
  line-height: 1;
  font-family: arial;
  display: inline;
}
<p>
  Oh hi i'm different
</p>

In the above snippet I've added a line-height of 1 to help normalize the spacing a bit. You could try to adjust further with setting the line-height to be at, or close to the exact font-size in pixels, but this will likely result in undesired spacing if you have lots of text in the element (text should also be in an appropriately semantic element like a p, or li, not just in a div).

In the end, can you achieve the result you're looking for? Definitely. Using things like line-height, margins and/or transforms. But you are likely not going to find a silver bullet to achieve the effect you want, consistently, if swapping out font faces.

As Sebastian Brosch mentioned in the question's comments, working off from Is it possible to change inline text height, not just the line-height? is likely going to be your best path forward.

Community
  • 1
  • 1
scottohara
  • 727
  • 4
  • 11