SVG display: none vs visibility: hidden Explained
While both display: none and
visibility: hidden make SVG elements invisible on the
screen, they interact differently with the SVG rendering tree, geometry
calculations, child inheritance, and pointer events. Understanding these
distinctions is crucial when manipulating vector graphics with CSS and
JavaScript, especially when calculating dimensions via
getBBox() or managing interactive vector states.
Rendering Tree and Bounding Box Calculations
The primary difference lies in how the browser constructs the SVG rendering tree and calculates geometry:
display: none: Completely removes the element from the rendering tree. The browser does not compute geometry for the element or its children. Calling.getBBox()on an element withdisplay: none(or an element containing onlydisplay: nonechildren) returns a zero-sized bounding box or throws an error in certain browser engines because layout coordinates do not exist.visibility: hidden: Hides the element visually but keeps it inside the rendering tree. The browser still parses the geometry, preserves its space within the SVG coordinate system, and includes it in parent bounding box calculations. Calling.getBBox()on avisibility: hiddenelement returns its actual geometric dimensions and position.
Inheritance and Child Overrides
The two properties handle CSS inheritance differently for nested SVG
elements (such as <g> groups):
display: none: Cannot be overridden by child elements. If a parent<g>tag hasdisplay: none, settingdisplay: inlineordisplay: blockon an inner<path>or<circle>will not render the child.visibility: hidden: Can be overridden by child elements. If a parent<g>hasvisibility: hidden, a child element set tovisibility: visiblewill still be drawn on the screen while the rest of the group remains invisible.
Pointer Events and Interactivity
Mouse and touch interaction behave differently based on SVG pointer event specifications:
display: none: The element cannot receive any user interaction under any circumstances. Setting CSSpointer-eventson a display-none element has no effect.visibility: hidden: By default, hidden elements do not capture pointer events. However, SVG supports specificpointer-eventsvalues (such aspointer-events: visiblePainted,pointer-events: visibleFill, orpointer-events: all) that allow an invisible element to still capture clicks, hover states, and touch events as an invisible hit target.
Performance and Use Cases
Use display: none when an SVG asset or path should be
fully deactivated, ignored during layout computations, and excluded from
assistive technologies to save rendering overhead.
Use visibility: hidden when you need to read layout
metrics using JavaScript, create invisible interaction hitboxes,
selectively show individual child nodes within a hidden group, or
animate visibility transitions smoothly.