Div widths not adding up? confused

Div widths not adding up? confused
0.0 0

#1

Hey campers,

in the snippet below, you’d expect the two nested divs to be on the same line since their individual width’s (50px) add up to their parent div’s width (100px). can anyone explain why that’s not the case?

https://jsfiddle.net/ahmedgadir/j1qwbz7t/

<head>
<style>
        * {
	 		padding: 0;
	 		margin: 0;
			box-sizing: border-box; 
		}

		.div1 {
			background: green;
			height: 50px;
			width: 100px;
		}

		.div2 {
			height: 50px;
			width: 50px;
			background: blue;
			display: inline-block;
		}

</style>
</head>
<body>

		<div class='div1'>
		    <div class='div2'></div>
		    <div class='div2'></div>
		</div>
</body> 

when the width of the parent div is increased to 104px then the expected behaviour is observed, however, it doesn’t really make sense as there shouldn’t be any margins separating the divs.

thank you for your time


#2

its ok i found the answer on stack overflow, im posting the solution so that if anyone else gets stuck on this then they know why.


#3

Just further to that, inline-block is saying “treat these elements like text”, and text has spaces between each word. It often doesn’t matter, and inline-block is fine. But for layout, generally use flex if you’re laying elements out in a line (or float, but that is a bit of a hack); if you use it, you generally need to apply further hacks to make it fit (eg remove all whitespace in the HTML).