Thursday, August 1, 2019

Best way to show/hide HTML elements without losing styling

There are basically three ways to do that:

  • element.style.visibility=hidden/visible works well when it comes to preserving styling but only hides the element while rendering it under the the hood. The element still takes up space in the page layout as if it was there (and it is there just that it does not show).
  • element.style.display=none/inline/block/initial works well in truly making the element disappear; the element does not show at all and it does not take any space in the page layout (as if it was not there at all). However, it will mess up (not preserve) the styling of certain elements, especially when complex CSS is involved.
  • element.hidden="true"/element.removeAttribute("hidden") works great, combining the true hiding of the latter with the styling preservation of the former. It is only supported in fairly new versions of browsers though as it was introduced with HTML5.

No comments:

Post a Comment