htmlcssimagedisplay

Why does a div with display: block (default) not expand to vertically fit an image without overflow but changing it to display: inline-block does?


I have a div with a background color via background-image:linear-gradient, and with the div's default display as block it doesn't expand vertically to fit the image, the image overflows over the bottom border of the div. When I change the display of the div to inline-block it expands vertically to fit the entire image. The image has float:left and a header and description is to the right of it within the div. I understand the basic difference between block, inline, and inline-block but based on their properties I can't work out in my head why changing the display of the div to inline-block allows it to expand to fit the image. The div has height and width set to auto and the image has a fixed height and width. It's a simple question I guess and I have it working the way I want it to. I'm just trying to understand why it works the way it does. Sorry if this is a noob question. Thanks!

It is working as I want it to, just trying to understand why its working the way it is, thanks!

Within html doc:

<div class="header2">
    <img class="logo2" src="Images/jailhousejournals4.PNG" alt="Journal and Coffee in 
    jail cell"> 
    <h2 style="vertical-align:top;">Correctional Compositions</h2>
    <p>The following entries were composed within Fayette County Detention Center, while 
    serving a three-month sentence. During that time I began to formulate my literary 
    voice, through reflection and contemplation of my life and the world I inhabit. </p>
  </div>

Within stylesheet:

.header2 {
  background-image: linear-gradient(to bottom, black 82%, blue);
  height: auto;
  width: auto;
  display: inline-block;
  font-family: "Seymour One", sans-serif;
  color: rgb(0, 100, 230);
  text-align: center;
  text-shadow: 2px 2px 0 grey, 2px 2px 6px black;
  font-size: 25px;
  margin-bottom: 5px;
  border: 2px hidden;
  border-radius: 8px;
  box-shadow: 0 3px 5px 4px rgb(100, 50, 150);
}
.logo2 {
    float: left;
    width: 200px;
    height: 180px;
    margin: 10px;
}

Solution

  • It works because inline-block combines characteristics of both inline and block elements.

    Block elements: These elements ignore floated elements because floats are removed from the normal document flow, which means the block element does not expand to include the floated elements' height.

    Inline elements: These elements include floated elements within their bounding box, which means they account for the height of the floated elements.

    Therefore, when you use inline-block, it behaves like a block element in terms of layout but also includes floated elements within its bounding box, allowing it to expand vertically to fit the content.