- How to Remove the Space Between Inline-block Elements
- Tricks to Remove the Space Between Inline-Block Elements
- Example of adding inline-block elements with space:
- Example of removing the space between inline-block elements with the margin-right property:
- Result
- Example of removing the space between inline-block elements with the font-size property:
- Example of removing the space between inline-block elements with Flexbox:
- Example of removing the space between inline-block elements with the float property:
- Борьба с пробелами между блочно-строчными элементами
- Другими словами
- Убрать пробелы
- Отрицательный внешний отступ
- Не использовать закрывающий тег
- Установить размер шрифта пробела, равный нулю
- Пусть они лучше плавают!
- Используйте вместо этого flexbox
- Removing the whitespace (Gap) between inline-block elements with CSS
- 1. Remove whitespaces between HTML tags
- 2. Remove whitespaces between HTML tags using comments
- 3. Using a negative margin
- 4. Monkeypatch the parent font size to 0
How to Remove the Space Between Inline-block Elements
Removing the space between inline-block elements is one of the most commonly asked questions on the internet. A series of inline-block elements usually will have space in between them.
Tricks to Remove the Space Between Inline-Block Elements
We can solve this problem with the help of CSS properties. Also, some tricks can remove the space between inline-block elements.
Let’s discuss the following example and give it a solution.
Example of adding inline-block elements with space:
html> html> head> title>Title of the document title> style> li < display: inline-block; width: 150px; font-size: 20px; color: #eeeeee; > li:nth-child(1) < background: #1c87c9; > li:nth-child(2) < background: #666666; > li:nth-child(3) < background: #8ebf42; > style> head> body> ul> li>Item 1 li> li>Item 2 li> li>Item 3 li> ul> body> html>
Here, we see the space between the inline-block elements. So let’s remove the spaces using some techniques.
ul> li>Item 1li>li>Item 2li>li>Item 3li> ul>
ul> li>Item 1 li>Item 2 li>Item 3 ul>
Let’s see another way of removing spaces using the margin-right property. In the following example, we set the margin-right: -4px; which removes the spaces between our elements.
Example of removing the space between inline-block elements with the margin-right property:
html> html> head> style> nav a < display: inline-block; background: #1c87c9; margin-right: -4px; color: white; font-weight: bold; text-decoration: none; font-size: 25px; > style> head> body> nav> a href="#">W a> a href="#">3 a> a href="#">docs a> nav> body> html>
Result
We can achieve the same result by setting the font-size property to 0 for .
Example of removing the space between inline-block elements with the font-size property:
html> html> head> style> nav < font-size: 0; > nav a < display: inline-block; background: #1c87c9; font-size: 25px; color: white; font-weight: bold; text-decoration: none; > style> head> body> nav> a href="#">W a> a href="#">3 a> a href="#">docs a> nav> body> html>
We can remove spaces with Flexbox . Read the comments to know why we should use extensions with the display property.
Example of removing the space between inline-block elements with Flexbox:
html> html> head> style> div < display: -webkit-box;/* OLD - iOS 6-, Safari 3.1-6 */ display: -moz-box;/* OLD - Firefox 19- (buggy but mostly works) */ display: -ms-flexbox;/* TWEENER - IE 10 */ display: -webkit-flex;/* NEW - Chrome */ display: flex;/* NEW, Spec - Opera 12.1, Firefox 20+ */ > strong < display: inline-block; width: 150px; font-size: 20px; padding: 20px; color: #eeeeee; text-align: center; > strong:nth-child(1) < background: #1c87c9; > strong:nth-child(2) < background: #666666; > strong:nth-child(3) < background: #8ebf42; > style> head> body> h2>Example of How to Remove the Space Between Inline-block Elements h2> div> strong>Item 1 strong> strong>Item 2 strong> strong>Item 3 strong> div> body> html>
The CSS float property can also come to help.
Example of removing the space between inline-block elements with the float property:
html> html> head> style> div < clear: both; content: " "; display: table; > span < display: inline-block; width: 150px; font-size: 18px; padding: 10px 15px; text-align: center; color: #eeeeee; float: left; > span:nth-child(1) < background: #1c87c9; > span:nth-child(2) < background: #666666; > span:nth-child(3) < background: #8ebf42; > style> head> body> div> span>Item List1 span> span>Item List2 span> span>Item List3 span> div> p>Some text p> body> html>
Борьба с пробелами между блочно-строчными элементами
Несколько раз встречал обсуждение проблемы пробелов в Твиттере, а затем увидел интересный дабблет на эту тему, поэтому решил зафиксировать.
Проблема вот в чём: между блочно-строчными элементами в браузере появляются пробелы, если вы форматируете HTML-код как обычно.
Другими словами
Такой пример кода даст следующий результат:
Это крайне нежелательное явление.
Нам часто нужно, чтобы элементы стояли друг к другу вплотную. Например, при вёрстке навигации это позволяет избавиться от неудобных маленьких некликабельных промежутков.
Это не «баг» (по крайней мере, я не думаю, что это баг). Просто так работает принцип расположения элементов в строчку. Ведь вы же хотите, чтобы между словами, которые вы печатаете через пробел, этот пробел был? Пробелы между этими блоками — почти то же самое, что пробелы между словами. При этом я допускаю, что спецификацию можно усовершенствовать и прописать, что пробелов между блочно-строчными элементами быть не должно, но я уверен, что мало кто решится открыть этот ящик Пандоры.
Вот некоторые способы борьбы с пробелами, чтобы заставить блочно-строчные элементы стоять вплотную друг к другу.
Убрать пробелы
Причина, по которой у вас получаются пробелы, в том, что у вас есть пробелы между элементами (на самом деле, перенос строки и знаки табуляции воспринимаются как пробел). Решить проблему поможет минимизированный HTML-код или любая из следующих хитростей:
Это всё довольно хитрые способы, но они делают своё дело.
Отрицательный внешний отступ
Можно подвинуть элементы, чтобы они стояли, как нужно, используя внешний отступ c отрицательным значением −4px . (возможны вариации значения в зависимости от размера шрифта у родительских элементов). Этот способ может некорректно работать в старых версиях IE (6 и 7), но если вам плевать на отображение в этих браузерах, вы хотя бы сможете сохранить в чистоте форматирование кода.
Не использовать закрывающий тег
Для HTML5 так делать — в порядке вещей. Хотя, стоит признать, становится немного не по себе.
Установить размер шрифта пробела, равный нулю
Пробел, имеющий нулевой размер шрифта, равен. нулю.
Мэтт Стоу сообщает, что метод использования
Другая странность! Даг Стюарт показал мне, что если использовать
Пусть они лучше плавают!
Может быть, им вообще необязательно быть блочно-строчными элементами, может, можно задать их расположение при помощи свойства float ? Это позволит вам задать им и ширину, и высоту, и внутренние отступы, и всё остальное. Но при этом вы не сможете выровнять их так же, как блочно-строчные элементы, используя свойство text-align: center; у родителя. Ну, вообще. вы в каком-то смысле сможете это сделать, но выглядит это очень странно.
Используйте вместо этого flexbox
Если вас устраивает список поддерживаемых браузеров, а также все, что вам нужно от блочно-строчных элементов — это их выравнивание по центру, вы вполне можете воспользоваться flexbox. Это не совсем замена блочно-строчным элементам, но вы сможете добиться от него того, чего хотите.
«Доктайп» — журнал о фронтенде. Читайте, слушайте и учитесь с нами.
Removing the whitespace (Gap) between inline-block elements with CSS
Learn how to deal with the problematic gap between your inline block elements.
Are you trying to create an inline grid with your own CSS rules using the inline-block display mode? Probably you are frustrated and asking to yourself «Why the hell is there a space between my elements!?». Even though your CSS may be very simple, you will always have a space between your HTML elements with the display: inline-block style. Consider the following snippet:
Already imagined what it should look like? Well, with a normal CSS imagination our expectation is:
However, you will get instead the following result:
In case you didn’t notice it neither, there’s a white space (in the second row highlighted in blue with an image editor) between every div with the head-item class. According to our style, we have simple blocks of 50×50 whose text is centered and its border is gray. Then, what is the problem? The markup, even executed inside an environment without other CSS rules will always display a Gap between every div with inline-block. This is by itself not a bug but the expected behaviour of an element using display: inline-block .
To solve this problem easily if the goal is to create an inline group of divs would be to set the float property of the class to left:
This would immediately produce our desired grid. However, this may not be useful in your cases and may not work with other styles. In this article we’ll share with you possible solutions that you may apply in your project against this problem.
1. Remove whitespaces between HTML tags
The first and most known solution to solve this issue is triming every space between the HTML elements that have the display: inline-block property, for example if we remove the spaces of our initial markup, we would have now:
The previous markdown (same but without spaces between the html tags) would succesful display our desired result of divs on a row without whitespaces:
As you can see, we didn’t need to add extra styles but just remove the whitespaces between the elements. If you want to use this solution, probably if you don’t want problem with other programmers about how messy is your code, then you may want to do this by using your server language e.g with PHP:
1 2 3 4 5