r/csshelp • • Aug 06 '20

Why are these two inline-blocks v-aligning differently?

I've got an inline-block <img>, and an inline-block <div>. They are different heights. I'd expect them to both v-align top, or both v-align bottom.

Instead, it looks like the <img> is v-aligning top, and the <div> is v-aligning bottom. In addition, the total height of the container is bigger than expected.

Why is this happening?

Screenshot

JS Fiddle

<div id="container">	
	<img id="logo" src="https://www.greyboxcreative.com/wp-content/uploads/2015/07/National-Geographic-logo-768x384.jpg">
	<nav id="top-nav">
		<ul>
			<li class="current_page_item">
				<a href="#">
					Home
				</a>
			</li>
			<li>
				<a href="#">
					About
				</a>
			</li>
		</ul>
	</nav>
</div>

#container {
	margin: 5px;
	border: 2px solid black;
}

#logo {
	display: inline-block;
	width: 200px;
	height: 75px;
	margin: 5px 15px;
	border: 2px solid red;
}

#top-nav {
	display: inline-block;
	text-transform: uppercase;
	font-size: 80%;
	border: 2px solid red;
}

#top-nav a {
	color: #CDCDCD;
	/* to move an underline down, need to turn off underline and use a border */
	text-decoration: none;
	padding-bottom: 3px;
	margin: 0 10px;
	line-height: 2;
}

#top-nav > ul {
	padding-left: 0;
	width: 100%;
}

#top-nav > ul > li {
	display: inline-block;
}

#top-nav > ul > li > ul {
	display: none;
}

#top-nav .current_page_item a {
	color: #1B84C9;
	border-bottom: 2px solid #1B84C9;
}
6 Upvotes

3 comments sorted by

2

u/Krirken Aug 07 '20

I believe the alignment is a result of how the spec calculates vertical-align. An img is a replaced element, and the CSS spec considers replaced elements as a special case in vertical alignment. From the spec (emphasis mine):

In the following definitions, for inline non-replaced elements, the box used for alignment is the box whose height is the 'line-height' (containing the box's glyphs and the half-leading on each side, see above). For all other elements, the box used for alignment is the margin box. [1]

I’m not sure what else the height of the container would be that is unexpected to you, but I hope that first part helps.

1: https://www.w3.org/TR/CSS2/visudet.html#propdef-vertical-align

2

u/RedDragonWebDesign Aug 07 '20

Thanks! Super subtle. I would have never found that on my own.

I used flex to solve the issue for now. I also found object-fit and object-position from your MDN article to be interesting. I'll have to play around with those.

2

u/Krirken Aug 07 '20

Glad I could help! Thanks for the award :D