问题
I'm trying to build a simple grid of divs: (live demo here)
HTML:
<div class="board"></div>
JS:
$(function() {
var boardHTML = '';
for (var r = 0; r < 2; r++) {
var row = '<div class="row">';
for (var c = 0; c < 5; c++) {
row += '<div class="cell"></div>';
}
row += '</div>';
boardHTML += row;
}
$('.board').append(boardHTML);
});
CSS:
.cell {
width: 30px;
height: 30px;
outline: 1px solid black;
display: inline-block;
}
.row {
background-color: red;
}
But, the result looks like this:

QUESTION: What causes this space between rows?
One possible solution is:
.row {
height: 30px;
}

Also, to get rid of the extra space on the right hand side, I could add:
.board {
width: 150px; /* 5 * 30px */
}

However, I wonder if there is a better solution which doesn't require setting the width/height in pixels.
Do you have any other ideas?
回答1:
Write like vertical-align: top; in your .cell CSS. Write like
.cell {
display: inline-block;
height: 30px;
outline: 1px solid black;
vertical-align: top;
width: 30px;
}
Check this http://jsfiddle.net/cSWnb/6/
回答2:
These settings are all behaving as expected so it's not clear exactly what you are hoping for.
Instead of setting the row height, you might instead play with the margins. Margins are what cause the space between block elements.
For the last item, try setting the width of the div to auto.
来源:https://stackoverflow.com/questions/9858154/html-divs-grid-unwanted-space-between-rows