skip to Main Content

please consider this code, why d3 and d4 are not aligned ?
what is the white space on top of d4 ?

.myContainer {
  display: block;
}

#d3 {
  width: 150px;
  height: 150px;
  border: 5px solid #aef704;
  padding: 25px;
  background-color: blueviolet;
  box-sizing: border-box;
  display: inline-block;
}

#d4 {
  width: 150px;
  height: 150px;
  border: 2px solid #aef704;
  padding: 25px;
  background-color: brown;
  box-sizing: border-box;
  display: inline-block;
}
<html lang="en">

<head>
</head>

<body>
  <div class="myContainer">
    <div id="d3">test content d3</div>
    <div id="d4">test content d4</div>
  </div>
</body>

</html>

those 2 divs should both rendered inline-block and should have 150px width and 150px height, then why the second one is a little bit lower than the first one.
here is what rendered :
white space on second div

3

Answers


  1. Because the default vertical alignment for inline elements is baseline. Change it easily by setting it to something like top instead.

    .myContainer {
      display: block;
    }
    
    #d3 {
      width: 150px;
      height: 150px;
      border: 5px solid #aef704;
      padding: 25px;
      background-color: blueviolet;
      box-sizing: border-box;
      display: inline-block;
    }
    
    #d4 {
      width: 150px;
      height: 150px;
      border: 2px solid #aef704;
      padding: 25px;
      background-color: brown;
      box-sizing: border-box;
      display: inline-block;
    }
    
    #d3,
    #d4 {
      vertical-align: top;
    }
    <div class="myContainer">
      <div id="d3">test content d3</div>
      <div id="d4">test content d4</div>
    </div>
    Login or Signup to reply.
  2. Alternatively, use flex which is more robust. See usage here: https://css-tricks.com/snippets/css/a-guide-to-flexbox/

    .myContainer {
      display: flex;
    }
    
    #d3 {
      width: 150px;
      height: 150px;
      border: 5px solid #aef704;
      padding: 25px;
      background-color: blueviolet;
      box-sizing: border-box;
      display: inline-block;
    }
    
    #d4 {
      width: 150px;
      height: 150px;
      border: 2px solid #aef704;
      padding: 25px;
      background-color: brown;
      box-sizing: border-box;
      display: inline-block;
    }
    <div class="myContainer">
      <div id="d3">test content d3</div>
      <div id="d4">test content d4</div>
    </div>
    Login or Signup to reply.
  3. add this to your main container holding the two divs.

    .myContainer {
      display: flex;
      flex-direction: row;
      align-item: center;
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search