Error using display: inline-block

Hi everyone, I am having issues aligning divs horizontally using CSS. Below is my code and you can visualize the page at CodePen.io. My goal is to have the yellow and white blocks horizontally aligned. Thanks for the help!

<style>
  body {
  background-color: gray;
}
#header-tabs {
  background-color: #34495E;
  width: 100%;
}
.inline-header {
  display: inline-block;
  width: 50%;
}

.inline-tabs {
  display: inline-block;
  width: 100px;
}

.tabs {
  text-align: center;
  margin-left: 50%;
}
#icon-container {
  margin-left: 40%;

}
.resize {
  height: 40px;
  width: auto;
}

.half-width {
  width: 50%;
}
</style>



<div id="header-tabs">
  <div class="inline-header half-width" style="background-color:yellow">
    <div id="icon-container">
      <img class="iniline-div resize imag-pos" src="https://d30y9cdsu7xlg0.cloudfront.net/png/2469-200.png" alt="mountain peaks">
    </div>

  </div>
  <div class="inline-header half-width tabs" style="background-color: white">
    <div class="inline-tabs">
      <p>About</p>
    </div>
    <div class="inline-tabs">
      <p>Portfolio</p>
    </div>
    <div class="inline-tabs">
      <p>Contact</p>
    </div>


  </div>
</div>
1 Like

There should be no whitespace between the inline <div>s. It pushes the second <div> downward since there’s no more space to the right.

<div class="inline-header">
  ...
</div><div class="inline-header">
  ...
</div>

or

<div class="inline-header">
  ...
</div><!--
--><div class="inline-header">
  ...
</div>

Then remove the .tabs's left margin.

You’ll notice some more space above and below those <div>s. Add vertical-align: top; in .inline-header (any valid value for vertical-align seems to do the same except baseline).


Or you could do away with inline block and use flexbox instead.

#header-tabs {
  display: flex;
}

.tabs {
  /* remove `margin-left` */
}

There’s no need to adjust the whitespace in the HTML. There’s also no need for vertical-align.

2 Likes

Hi boy, first you seem to have good taste on design not like me :smile:
Now for your alignment issue, the solution is to change a little your CSS :

  1. You need first to remove your margin-left on .tabs
  2. Then modify the width from 50% to 49,99% on .half-width and .inline-header

Apparently for some reasons, when you put inline-block in a block element, all the child element need to have a width less than the parent.

EDIT: It seem that is possible to children to have the same width than his parent. For that you need to be careful about the spacing (space and new line) in your source code. Because, inline-block react like words in p tags. Look at the first example of kevcomedia above.

Percentage values specified as floating point number is not supported across all the browsers.
It’s always a good practice to get rid of white space between elements displayed as inline-block.
Either by commenting the white space or by physically removing the white space.

1 Like