Shinji-san Shinji-san - 1 year ago 54
CSS Question

Shrinking a div to content size

Hello I was wondering is there a way to shrink a div down to its content size(I ask because I have a background color and it just looks ugly when the text height is much shorter than the rest of the div,, which is filled with color? When I put height: auto it's not really shrinking down to the content size; by that I mean the text that I have. Is there a way to provide room past the text cumulative height? Like having the div height be 10 or 15 percent higher than the total height of the content? If you see I put margin:auto on here but it's not really having an effect. Right now this div is in a flexbox but I don't think that's causing the issue. Now in the snippet the height ratio is perfectly fine, but when I do it in a bigger window the height of the div completely overshadows the text because of the color/height of the div. And I'd rather not increase the line-height. Or do I just have to do trial and error and just change the height values until I find something?


.middle {
display: flex;
flex-flow: column wrap;
order: 2;
justify-content: center;
align-items: center;

.middle div {
height: auto;


.box2 {

background-color: #F0ECCA;


<div class="middle">

<div class="box">
<h2> Overview <h2>


<div class="box2">
<p>"Yo yo dab dab sample sample sample
this is a sample sentence this is a sample sentence this is a sample sentence this is a sample sentence this is a sample sentence this is a sample sentence.



Answer Source

The div that holds the text is doing exactly what you expect it to. The excess background color is actually coming from the <p> tag. Setting the margin-top and margin-bottom both to 0 for that element will do what you are looking for.

Why do we need to manually change the margins of the <p>? <p> tags have default margins provided by the browser.

How do you easily solve issues like this? Open the inspector and choose the "select an element" button (top-left in the chrome console). Hover over the element you are trying to fix and look at the style values and box model provided by the console.