Jainil Ajmera Jainil Ajmera - 7 months ago 17
HTML Question

Images not appearing on the same line with display:inline-block

In order to position two images beside each other (i.e. the two images are on the same line), I tried the following code:

<html>
<head>
<style>

#container {
width:100%;
}

img {
display:inline-block;
width:50%;
}

</style>
</head>

<body>
<h1 style="text-align:center"><strong>Test</strong></h1>
<div id="container">
<img src="Google-logo.png">
<img src="Google-logo.png">
</div>
</body>




The width of the container div should be shared equally by the two images, right? However, this does not happen and the images appear on two separate lines.

If, however, I use float:left instead, the images do appear on the same line. Why is this?

Answer

Remove the new line between the img tags:

<div>
    <img src="..." alt=""><img src="..." alt="">
</div>

This happens because elements which are declared with inline or inline-block are sensitive to whitespace.

More information: on David Walsh's Blog

Commonly layouts are done with floats or flexbox instead.

Floats

/* Clearfix */
.wrapper:after {
  content: '';
  display: table;
  clear: both;
}

.item {
  float: left;
  width: 50%;
  height: 100px;
}

.item-1 {
  background: red;  
}

.item-2 {
  background: blue;  
}
<div class="wrapper">
  <div class="item item-1"></div>
  <div class="item item-2"></div>
</div>

Flexbox

.wrapper {
  display: flex;
}

.item {
  flex: 1; /* Or use width: 50%; */
  height: 100px;
}

.item-1 {
  background: red;  
}

.item-2 {
  background: blue;  
}
<div class="wrapper">
  <div class="item item-1"></div>
  <div class="item item-2"></div>
</div>

Comments