SrikanthReddy Karnati SrikanthReddy Karnati - 4 months ago 8
HTML Question

How to position div without space

I have six divs in my html document.

My problem is that last div has some top space which needs to be removed.

This is not a duplicate question.

This has nothing to do with inline-block spacing.

Please help.



<!DOCTYPE html>
<html>
<style>
body {
border: 1px solid;
padding: 0;
margin: auto;
height: 500px;
width: 500px;
}
div {
padding: 0;
margin: 0;
border: 1px solid;
display: inline-block;
width: 25%;
height: 25%;
position: relative;
}
div:first-child {
background: black;
}
</style>

<body>
<div></div>
<div></div>
<div></div>
<div></div>
<div>
</div>
<div>
<div></div>
</div>
<script>
var myDivs = document.querySelectorAll("div");
myDivs[2].style.backgroundColor = "blue";
</script>
</body>

</html>




Answer

This is a problem with inline-block. Use vertical-align: top to fix, as the default is baseline:

<!DOCTYPE html>
<html>
<style>
  body {
    border: 1px solid;
    padding: 0;
    margin: auto;
    height: 500px;
    width: 500px;
  }
  div {
    padding: 0;
    margin: 0;
    border: 1px solid;
    display: inline-block;
    width: 25%;
    height: 25%;
    position: relative;
    vertical-align: top;   /* This is the fix */
  }
  div:first-child {
    background: black;
  }
</style>

<body>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div>
  </div>
  <div>
    <div></div>
  </div>
  <script>
    var myDivs = document.querySelectorAll("div");
    myDivs[2].style.backgroundColor = "blue";
  </script>
</body>

</html>