📜 ⬆️ ⬇️

Inline-block as a replacement for float

Half a year ago I did a translation of an article on Habré. Details about the float property . This time, take a look at it from a slightly different angle. When developing a site, we often use floats to position some blocks on a page, such as sidebar. But is it necessary?

Float is not always convenient: for example, when you make a grid with an image. Sometimes it is appropriate to use inline-block, which mimics the behavior of a float.

What is inline-block?


The usual block element structure is:
')


Inline-block is a value that can be assigned to the display property. The name comes from some characteristics of both lowercase and block elements.



Inline block vs float: differences






View Demo

To combat the gaps, you can use several techniques. Remove spaces in lists:

<ul> <li> one</li><li> two</li><li> three</li> </ul> 


Using a negative margin value:

 nav a { display: inline-block; margin-right: -4px; } 


The strange way with the absence of a closing LI tag:

 <ul> <li>one <li>two <li>three </ul> 


Setting the font-size value to zero:

 nav { font-size: 0; } nav a { font-size: 16px; } 


More details about these methods can be found in the article CSS-tricks .

What to use?


The choice between inline-block and float must be made on the basis of the tasks to be solved in a particular design. In the end, it all comes down to the differences between these two tools:



Image grid


Such grids are used in photo galleries. In this example, we can well illustrate the behavior of inline-block and float. The use of float is justified if the images are the same height. If the height is different, the elements may appear crooked:



Inline-block'and do not have such a problem, because they are located on the same level in the line. Therefore, inline-block is better suited for the layout of the gallery:



Watch the demonstration

Conclusion


We are used to using float to solve many problems in page layout. However, it is sometimes easier and more convenient to use inline-block. And sometimes it is more correct to use good old tables.

Used materials and useful links on the topic:

Source: https://habr.com/ru/post/161581/


All Articles