HTML divs grid - unwanted space between rows [duplicate]

左心房为你撑大大i 提交于 2020-04-16 04:47:31

问题


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:

enter image description here

QUESTION: What causes this space between rows?

One possible solution is:

.row {
    height: 30px;
}

enter image description here

Also, to get rid of the extra space on the right hand side, I could add:

.board {
    width: 150px; /*   5 * 30px   */
}

enter image description here

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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!