Skip to content

Instantly share code, notes, and snippets.

@ollicle
Last active September 30, 2023 12:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ollicle/d7d036c79501240f3abb9958d64b73f8 to your computer and use it in GitHub Desktop.
Save ollicle/d7d036c79501240f3abb9958d64b73f8 to your computer and use it in GitHub Desktop.
A CSS hidden property

The CSS display property is overloaded

  • How the element will contribute to layout/flow: display:block/inline/flex/etc…
  • Should the element contribute to layout/flow: display:none

It would be useful to have the means to separate these concerns.

A property to handle display:none

Given this HTML:

<div class="bar has-flex-items">
	<div class="item">…</div>
	<div class="item hidden-small-only" hidden>…</div>
</div>

And this fanciful CSS:

/* Proposing a `hidden` CSS property that determines if the element *should* contribute to layout/flow */
[hidden] {
	hidden: hidden; /* declare element should not display – equivalent to `display:none` */
}

/* The `hidden` property is not overriden by `display` – */
/* permitting the layout properties to be assigned latently */
.has-flex-items .item {
	display: flex;	/* The element remains hidden */
}

@media (min-width: 40em) {
	/* Restore the display layout behaviour without redefining it */
	.hidden-small-only {
		hidden: display; /* restore the default value */
	}
}

Existing workarounds

As it stands we need to repeat the display layout when using display to hide the element.

Given an element to hide and show:

<div class="item">…</div>

Hide it with hidden:

<div class="item" hidden>…</div>

Until display is set:

.item { display: flex }

Then hidden may need a specificity bump:

[hidden] { display: none }

Override on large screens?

@media (min-width: 40em) {
	.item[hidden] {
		display: flex;
	}
}

Using a class instead of HTML hidden attribute

Increasing the importance of the hidden attribute to ensure hidden means hidden.

[hidden] {
	display: none !important;
}

Use a class to clearly signifiy we are only hiding the element sometimes:

<div class="item hidden-small-only">…</div>

Hide the element and override with a media query:

.hidden-small-only {
	display: none;
}

@media (min-width: 40em) {
	.hidden-small-only {
		display: flex;
	}
}

With display value dependent on a parent

<div class="bar has-flex-items">
	<div class="item">…</div>
	<div class="item hidden-small-only">…</div>
</div>

Repeat the override, because specificity:

.item {
	display: block;
}

.has-flex-items .item {
	display: flex;
}

@media (min-width: 40em) {
	
	.item.hidden-small-only {
		display: block;
	}
	
	.has-flex-items .item.hidden-small-only {
		display: flex;
	}
	
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment