Home > front end >  Set div height to letter size
Set div height to letter size

Time:10-20

Given the following HTML:

<div>
  Ag<div ></div>
</div>
<div>
  Ag<div ></div>
</div>

I want the size of .rect to be the size of the largest character box, so it should align with the ascender height (the A in this example) and go down to the descender height (the g in this example).

A possible solution is to set the height of .rect to the line height and to write an &nbsp; inside it:

body {
  line-height: 1.5em;
}
.rect {
  height: 1.5em;
  width: 10rem;
  display: inline-block;
  background-color: red;
}
<div>
  Ag<div >&nbsp;</div>
</div>

But I'm dissatisfied with this solution because it requires me to make sure the div height is consistent with the local line height and the additional &nbsp; is just noise. Also, setting .rect to the line height, isn't strictly what I want because it could be larger or smaller than the actual characters.

Is there an alternative solution?

CodePudding user response:

You can use Flex for more https://developer.mozilla.org/en-US/docs/Web/CSS/flex

.wrap {
  display: flex;
}

.rect {
  width: 10rem;
  background-color: red;
}
<div >
  Ag<div ></div>
</div>

CodePudding user response:

this seems to work. According to the css spec, setting line height to just a number: The used value is this unitless multiplied by the element's own font size. The computed value is the same as the specified . In most cases, this is the preferred way to set line-height and avoid unexpected results due to inheritance.

https://developer.mozilla.org/en-US/docs/Web/CSS/line-height

<head>
<style>
body {
  line-height: 1.5em;
}
.rect {
  width: 10rem;
  display: inline-block;
  background-color: red;
  line-height: 1;
}

.wrapper{
    border: 1px solid red;
}
</style>
</head>
<body>
<div >
  Ag<div >&nbsp;</div>
</div>
</body>

  • Related