Why does CSS not support negative padding?

前端 未结 7 1446
予麋鹿
予麋鹿 2020-11-30 01:26

I have seen this many a times that the prospect of a negative padding might help the development of CSS of certain page elements become better and easier. Yet, there is no p

7条回答
  •  猫巷女王i
    2020-11-30 02:03

    Because the designers of CSS didn't have the foresight to imagine the flexibility this would bring. There are plenty of reasons to expand the content area of a box without affecting its relationship to neighbouring elements. If you think it's not possible, put some long nowrap'd text in a box, set a width on the box, and watch how the overflowed content does nothing to the layout.

    Yes, this is still relevant with CSS3 in 2019; case in point: flexbox layouts. Flexbox items' margins do not collapse, so in order to space them evenly and align them with the visual edge of the container, one must subtract the items' margins from their container's padding. If any result is < 0, you must use a negative margin on the container, or sum that negative with the existing margin. I.e. the content of the element effects how one defines the margins for it, which is backwards. Summing doesn't work cleanly when flex elements' content have margins defined in different units or are affected by a different font-size, etc.

    The example below should, ideally have aligned and evenly spaced grey boxes but, sadly they aren't.

    body {
      font-family: sans-serif;
      margin: 2rem;
    }
    body > * {
      margin: 2rem 0 0;
    }
    body > :first-child {
      margin-top: 0;
    }
    h1,
    li,
    p {
      padding: 10px;
      background: lightgray;
    }
    ul {
      list-style: none;
      display: flex;
      flex-wrap: wrap;
      padding: 0;/* just to reset */
      padding: -5px;/* would allow correct alignment */
    }
    li {
      flex: 1 1 auto;
      margin: 5px;
    }

    Cras facilisis orci ligula

    • a lacinia purus porttitor eget
    • donec ut nunc lorem
    • duis in est dictum
    • tempor metus non
    • dapibus sapien
    • phasellus bibendum tincidunt
    • quam vitae accumsan
    • ut interdum eget nisl in eleifend
    • maecenas sodales interdum quam sed accumsan

    Fusce convallis, arcu vel elementum pulvinar, diam arcu tempus dolor, nec venenatis sapien diam non dui. Nulla mollis velit dapibus magna pellentesque, at tempor sapien blandit. Sed consectetur nec orci ac lobortis.

    Integer nibh purus, convallis eget tincidunt id, eleifend id lectus. Vivamus tristique orci finibus, feugiat eros id, semper augue.

    I have encountered enough of these little issues over the years where a little negative padding would have gone a long way, but instead I'm forced to add non-semantic markup, use calc(), or CSS preprocessors which only work when the units are the same, etc.

提交回复
热议问题