Perfectly Center Any Element on Your Page – center-that-thing

Category: Javascript , Layout | November 30, 2023
Author:peter-kuhmann
Views Total:26 views
Official Page:Go to website
Last Update:November 30, 2023
License:MIT

Preview:

Perfectly Center Any Element on Your Page – center-that-thing

Description:

center-that-thing is a lightweight JavaScript library that allows you to easily center any element relative to the screen, even if its parent container is offset. It dynamically tracks the element size and window size to keep your element centered.

Its collision detection feature lets you specify that the centered element should avoid overlaying sibling elements next to it. This prevents your centered popup or modal from covering important navigation or headers.

How to use it:

1. Download the package and load the minified version of the center-that-thing library in the document.

<script src="/dist/center-that-thing.min.js"></script>

2. Call the function centerThatThing()< on the element which should be centered.

centerThatThing(yourElementSelector);

3.1. Or add the data-ctt-enable="true" attribute to that element.

<div data-ctt-enable="true">
  I'll be centered
</div>

3.2. Call the function enableCenterThatThingDynamicDiscovery() for elements dynamically added to the page.

enableCenterThatThingDynamicDiscovery()

4. You can also implement the center-that-thing via CSS.

:root {
--center-that-thing: '[{"selector": "nav > .logo"}, {"selector": "footer > .logo", "collisionDetection": "siblings"}]';
}

5. Enable the collision detection feature.

centerThatThing(yourElementSelector,{
  collisionDetection: 'siblings'
});
<!-- OR -->
<div
  data-ctt-enable="true"
  data-ctt-collision-detection="siblings">
  I'll be centered
</div>

You Might Be Interested In:


Leave a Reply