Change record status: 
Project: 
Introduced in branch: 
10.0.x
Introduced in version: 
10.0.0
Description: 

The displace method finds elements in the DOM marked with one of four attributes: data-offset-top, data-offset-right, data-offset-bottom or data-offset-left. For more information see the change record that introduced Drupal.displace.

With Drupal 10.0.0 and later, the displace method now sets a CSS custom property (CSS Variable) on the root <html> element with the format of --drupal-displace-offset-[edge]: [value]px;, where [edge] is the offset edge, and [value] is a number.

Examples of inline styles added to the HTML element:

Items at the top of the page (in this case toolbars) take up 79px of space.

--drupal-displace-offset-top: 79px;

Items at the right of the page (in this case the settings tray) take up 300px of space.

--drupal-displace-offset-right:300px;

Items to the left of the page (in this case the toolbar in vertical mode) take up 240px of space

--drupal-displace-offset-left:240px;

Use case

In many cases the developer needs to fix a HTML element to the edge of the page. However, when using CSS such as top: 0, or right: 0, the element may appear underneath or overlap other fixed elements.

This is the use case for Drupal.displace() . Previously the developer would need to run Drupal.displace(), which would return all of the offsets. This still works, however you can now properly position elements without the need for JavaScript.

Positioning using CSS Variables

Instead of running Drupal.displace() to get the offsets, and then inject the values via inline-styles, you can now query the custom CSS properties:

To position at the top of the page (and underneath any other fixed elements), use CSS similar to the following. Note the second parameter within the CSS variables var() function, which sets the value to zero if the first parameter does not exist. See MDN for more information.

.my-fixed-top-element {
  position: fixed;
  top: var(--drupal-displace-offset-top, 0px);
}

Note that Drupal.displace() does not take into account RTL languages, so it’s up to the individual components to decide to set the data-offset-left or data-offset-right attributes. This means that the CSS needs to accommodate this limitation.

To position to the left of the page in LTR languages, and to the right in RTL languages, use the following CSS.

.my-fixed-left-element {
  position: fixed;
  left: var(--drupal-displace-offset-left, 0px);
}
/* To support RTL languages */
[dir="rtl"] .my-fixed-left-element {
  position: fixed;
  left: auto;
  right: var(--drupal-displace-offset-right, 0px);
}
Impacts: 
Themers

Comments

nod_’s picture

This still need to have the core/drupal.displace library as a dependency of your CSS file for the css var to be created and updated.