Difference between “visibility:collapse” and “display:none”

前端 未结 5 1680
醉酒成梦
醉酒成梦 2020-11-30 01:43

What is the difference between visibility:collapse and display:none?

5条回答
  •  半阙折子戏
    2020-11-30 02:17

    visibility: collapse behaves exactly like visibility: hidden in most formatting contexts: the space required by the element is 'reserved' in the layout, but the element itself is not rendered, leaving a blank space where it would have been.

    There are three exceptions that I know of: table-rows, table-columns and flex items, in which visibility: collapse behaves like display: none, but with one major difference: the 'strut'. You can think of the strut as a zero-sized placeholder, that doesn't claim any space of its own in the layout process, but is nevertheless still part of the formatting structure and participates in some size computations.

    A collapsed table-row, for example, will not occupy any vertical space in the table, but the table columns will still be dimensioned 'as-if' the collapsed row and its contents were actually visible. This is to prevent columns from 'wobbling' as rows are toggled in and out. Likewise, a collapsed flex item doesn't occupy any space along the main axis, but still contributes to the flex line cross-size.

    'Do not use display: none with tables' is a valuable rule of thumb, but it doesn't tell the whole story.

    • Use display: none if you don't want your hidden elements to participate in any way in the table (or flex line) layout process.
    • Use visibility: collapse if you want to dynamically show and hide elements without destabilizing the table (or flex line) layout.

    Here is a code snippet demonstrating the difference between display: none and visibility: collapse for a table row:

    .show-right-border {
      border-right: 1px black solid;
    }

    visibility: collapse

    Short text. Loooooooooong text.

    display: none

    Short text. Loooooooooong text.

提交回复
热议问题