У меня есть такая HTML-структура:
<div id='root'>
<div class='tile-row'>
<div class='tile'></div>
<div class='tile'></div>
</div>
<div class='tile-row'>
<div class='tile'></div>
<div class='tile'></div>
</div>
</div>
Фактически есть 10 рядов плиток и 10 плиток в ряду.
Я использую следующую дерзость:
body, html
overflow-x: scroll
padding: 0
margin: 0
background-color: black
color: white
.tile-row
display: block
margin: 0
padding: 0
.tile
display: inline-block
outline: 1px solid white
width: 10px
height: 10px
Проблема в том, что между строками есть граница / поле, от которых я не знаю, как избавиться. Я хочу, чтобы клетки были прямо напротив друг друга. здесь - его код. Вот скриншот:






Добавьте line-height: 0 к вашему .tile-row или измените его дисплей на что-то другое, кроме inline-block (например, на любой дисплей table-*, grid или flex).
Объяснение:
Из спецификации CSS, доступной на https://www.w3.org/TR/CSS2/visudet.html#line-height
As described in the section on inline formatting contexts, user agents flow inline-level boxes into a vertical stack of line boxes. The height of a line box is determined as follows:
The height of each inline-level box in the line box is calculated. For replaced elements, inline-block elements, and inline-table elements, this is the height of their margin box; for inline boxes, this is their 'line-height'. (See "Calculating heights and margins" and the height of inline boxes in "Leading and half-leading".)
The inline-level boxes are aligned vertically according to their 'vertical-align' property. In case they are aligned 'top' or 'bottom', they must be aligned so as to minimize the line box height. If such boxes are tall enough, there are multiple solutions and CSS 2.1 does not define the position of the line box's baseline (i.e., the position of the strut, see below).
The line box height is the distance between the uppermost box top and the lowermost box bottom. (This includes the strut, as explained under 'line-height' below.)
Empty inline elements generate empty inline boxes, but these boxes still have margins, padding, borders and a line height, and thus influence these calculations just like elements with content.
и в других частях спецификации:
inline-block This value causes an element to generate an inline-level block container. The inside of an inline-block is formatted as a block box, and the element itself is formatted as an atomic inline-level box.
а также:
Inline-level elements are those elements of the source document that do not form new blocks of content; the content is distributed in lines
Вывод состоит в том, что тайлы встроенных блоков считаются действительно большими символами, а высота строки просто влияет на них, делая строки немного больше, чем символы.
Соответствующие ссылки:
Я явно имел в виду высоту строки. Изменение размера шрифта тоже сработает, но убьет все, что написано внутри .title-row, если OP хочет что-нибудь в нем записать. Обновлено: Дело в том, что плитки встроенного блока считаются как действительно большие персонажи, а высота строки просто влияет на них, делая строки немного больше, чем символы, хотя не верьте мне на слово.
line-height влияет на текст, а не на расположение ячеек. OP не упомянул, что текст помещается в элементы .tile. Как работает этот ответ?
Сами .tiles представляют собой текст для .tile-row, поскольку они являются встроенными блоками, вы можете проверить спецификацию для деталей. Или вы можете просто добавить его в JSFiddle и убедиться, что он работает.
Отредактировал свой ответ, чтобы дать подробное объяснение.
Проблема возникает из display: inline-block, другим решением может быть font-size: 0; или дисплей: flex вместо inline-block
.tile-row
display: block
margin: 0
padding: 0
font-size: 0
Не забудьте вернуть размер шрифта для .tile, если вы используете решение font-size: 0.
Хотя настройка высоты строки может помочь, поскольку вы знаете, насколько велика ваша сетка по ширине, вы можете установить ширину самой сетки, а затем заставить элементы перемещаться влево. Зная, что каждая ячейка имеет размер 20x20, максимальная ширина сетки будет 200. Вот мое решение для вашей сетки:
.tile-row
display: block
margin: 0
padding: 0
max-width: 200px
.tile
display: inline-block
float: left
outline: 1px solid white
width: 20px
height: 20px
используйте display:table-cell для вашего .tile
.tile
display: inline-block
outline: 1px solid white
width: 20px
height: 20px
display: table-cell
Может, стоит попробовать:
position: relative
float: left
margin: 0
padding: 0
Если он все еще не работает, у вас может быть другой код CSS, влияющий на ваш элемент. Вы можете изменить это с помощью! Important, например: margin: 0 !important.
Удачи!
line-heightвлияет на базовую линию текста. ты проheight?