📜 ⬆️ ⬇️

Negative indents - the path to universality

I often come across a situation where in a series of blocks with identical indents and a common container, the first or last block does not have an indent or is different from the others. For some time I used crutches, like the classes first or last, to solve this “problem” until I mastered the technique of working with negative indents.


The use of negative indents opens up wide possibilities and allows you to make the layout more universal. In order to sort things out, let's create a small container filled with blocks, something like a gallery.

Container filled with blocks
')
For example, I tried to pick the most difficult situation. In this case, we need to neutralize not only the indent from the top of the first row, but the indent on the left of the first column, while fitting the blocks in the div container neatly into three columns.

HTML:

  1. <div>
  2. <ul>
  3. <li> 1</li>
  4. <li> 2</li>
  5. <li> 3</li>
  6. <li> 4</li>
  7. <li> 5</li>
  8. <li> 6</li>
  9. <li> 7</li>
  10. <li> 8</li>
  11. </ul>
  12. </div>


CSS:

  1. div {
  2. border: 2px solid #CCC;
  3. overflow: hidden;
  4. width: 640px;
  5. }
  6. ul {
  7. margin: -20px 0 0 -20px;
  8. overflow: hidden;
  9. padding: 0;
  10. }
  11. ul li {
  12. background: #C06;
  13. float: left;
  14. height: 100px;
  15. list-style: none;
  16. margin: 20px 0 0 20px;
  17. width: 200px;
  18. }
  19. *html ul {
  20. width: 660px;
  21. }
  22. *html ul li {
  23. display: inline;
  24. }


The problem is solved and now let's focus on the main points. The center point is the negative values ​​of the margin property for the ul tag, and the overflow property with the hidden value for the div tag. With their help, we move the ul block relative to the div block beyond its border by 20px up and to the left, and with the help of overflow we cut off the indents we don't need. In these two properties lies the essence of the method.

Negative indents beyond the container

But as always there is one “but” or even three, this is the overflow property for the ul tag and two separate properties for the IE 6.0 browser. The first property is used to neutralize the effect of the float property on the parent block. And for IE 6.0, I separately used the width property for the ul block, since IE cannot calculate it itself relative to the child blocks, and the display property to eliminate duplication of indents when the float property is applied to the block.

The presented example was tested in browsers: IE 6.0+, Firefox 2.0, Opera 9.0, Safari 2.0+. Once again I want to say that this technique is universal and can be applied everywhere, where necessary, in various variations. Experiment and share your experience :)

Example

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


All Articles