Home > other >  Use CSS and HTML to set parent container to content height minus X pixels
Use CSS and HTML to set parent container to content height minus X pixels

Time:11-17

I have a HTML setup:

<div id="wrapper">
    <div id="content">
        Lorem ipsum, dolor sit amet consectetur adipisicing elit. Ex corporis perferendis in fugiat cumque. Ipsam modi quia doloremque, animi quisquam quo exercitationem nihil debitis ea corrupti, provident placeat officiis nam.
    </div>
</div>

I would like the height of the div with id wrapper to be equal to the height of the div with id content, minus X px (say 4px).

The div with id wrapper must be positioned according to the normal flow of the document. I.e. not absolute or fixed.

Is this possible?


I am asking because I would like to remove the top and bottom spacing of the text, (not padding, border, margin), but keep spacing between the text in case of wrapping.

Essentially; If the text would never wrap, (which it can), it would be equal to setting the line-height to 1 (or the font size).

EDIT: Asked another way, can i set line-height to 1 for only the top half of the first line, and the bottom half of the last line?

If there are any other ways of accomplishing this, I.e css properties like paragraph-height or similar, this is very welcome.

CodePudding user response:

It's difficult to understand precisely what you need here, but if you want the parent to be the same height as its child but minus a few pixels, you could add a negative margin to the child to reduce the parent's height.

#wrapper{
  background: red;
  display: inline-block;
}

#content {
  margin-bottom: -4px;
  margin-top: -4px;
}
<div id="wrapper">
    <div id="content">
        Lorem ipsum, dolor sit amet consectetur adipisicing elit. Ex corporis perferendis in fugiat cumque. Ipsam modi quia doloremque, animi quisquam quo exercitationem nihil debitis ea corrupti, provident placeat officiis nam.
    </div>
</div>

CodePudding user response:

In CSS you can use calc() to make calculations.

#content{
  height: calc(100% - 4px)
}

  • Related