How do I put divs on a line with "display: inline-block", no margin?
Whenever I put divs on a horizontal line with display:inline-block
, there is always a margin between them, even if I set margin: 0 !important
. Is there a way to have exactly 0 pixels between divs?
Here is a basic example where I have three black boxes that should be contiguous but there is a space between them: ( Fiddle )
.div {
position: relative;
display: inline-block;
background: black;
width: 100px;
height: 100px;
margin: 0 !important;
}
<div class="div"></div>
<div class="div"></div>
<div class="div"></div>
source to share
This is because of the new line between the elements. You could comment on this as I did, or make these elements inline with each other.
.div {
position: relative;
display: inline-block;
background: black;
width: 100px;
height: 100px;
margin: 0 !important;
}
<div class="div"></div><!--
--><div class="div"></div><!--
--><div class="div"></div>
source to share
You must point font-size: 0
to the parent container. The font size gives these small margins to inline boxes.
.div {
position: relative;
display: inline-block;
background: black;
width: 100px;
height: 100px;
margin: 0 !important;
}
.container {
font-size: 0;
}
<div class="container">
<div class="div"></div>
<div class="div"></div>
<div class="div"></div>
</div>
source to share
.divlist {
position: relative;
font-size: 0;
}
.div {
position: relative;
display: inline-block;
background: black;
width: 100px;
height: 100px;
font-size: 16px;
}
<div class="divlist">
<div class="div"></div>
<div class="div"></div>
<div class="div"></div>
</div>
source to share
Better to have an outer div and add style 0 font size
For example:
.div {
position: relative;
display: inline-block;
background: black;
width: 100px;
height: 100px;
margin: 0 !important;
font-size: 14px;
color:#fff;
text-align:center;
}
.main-div {
font-size:0;
}
<div class="main-div">
<div class="div">1</div>
<div class="div">2</div>
<div class="div">3</div>
</div>
source to share
Use display: table-cell;
.div {
position: relative;
display: table-cell;
background: black;
width: 100px;
height: 100px;
}
<div class="div"></div>
<div class="div"></div>
<div class="div"></div>
source to share
I know this is not the cleanest solution, but this is how I do it:
.div {
display: inline-block;
background: black;
width: 100px;
height: 100px;
white-space: nowrap;
overflow: hidden;
margin-right : -0.25em;
}
<div class="div"></div>
<div class="div"></div>
<div class="div"></div>
Inline-block unwanted margin is well known and you will find other solutions here
source to share
I added a wrapper defined as flexbox.
.wrapper {
display: inline-flex;
}
.div {
position: relative;
display: inline-block;
background: black;
width: 100px;
height: 100px;
}
<div class="wrapper">
<div class="div"></div>
<div class="div"></div>
<div class="div"></div>
</div>
source to share