Onjsdev

Share


How to Center an Element with a Sticky Item Next to It


By onjsdev

Dec 25th, 2023

While developing a web page, I needed to center an element on the page and add another sticky element next to it. The problem is that only the content needs to be centered, not the sticky element. Here is the solution I came up with.

HTML Content

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />

  </head>
  <body>
    <div class="container">
      <div class="content">
        <!-- Your main content goes here -->
        <h1>Lorem ipsum dolor sit amet, consectetur adipiscing elit...</h1>
      </div>
      <div class="sticky">
        <!-- Your sticky element goes here -->
        <p>I stick next to the content!</p>
      </div>
    </div>
  </body>
</html>
  • We have a container div (.container) that will hold both the main content and the sticky element.
  • Inside the container, there's a content div (.content) for your main content and a sticky div (.sticky) for the sticky element.

CSS Styling

   <style>
      * {
        box-sizing: border-box;
        margin: 0;
        padding: 0;
      }
      /* Container for the sticky and content elements */
      .container {
        display: grid;
        grid-template-columns: repeat(1, minmax(0, 1fr));
        align-items: start;
        justify-content: center;
      }
      /* Content element */
      .content {
        width: 400px;
        height: 1000px;
        background-color: aquamarine;
        grid-row-start: 1;
        grid-column-start: 1;
      }

      /* Sticky element */
      .sticky {
        position: sticky;
        grid-row-start: 1;
        grid-column-start: 1;
        width: 200px;
        transform: translateX(-100%);

        /* stick to Right
        margin-left: auto;
        transform: translateX(100%);
        */
        top: 0;
        background-color: red;
        /* Add additional styles as needed */
      }
    </style>
  • The container uses CSS Grid to center its contents horizontally.
  • The grid-row-start: 1; and grid-column-start: 1; declarations for both the .content and .sticky classes are indeed used to place these two elements on top of each other within the grid, without using position absolute.
  • The sticky div is set to a sticky position, and transform: translateX(-100%) is used to position it to the left of the content.
  • Use margin-left auto with translateX(100%), if you want element to stick the right side.

Conclusion

Feel free to experiment and customize the code to suit your needs. Adjust the width, height, and styling to match your desired layout. You can also modify the position and appearance of the sticky element according to your design preferences.

Now that you have a basic understanding of creating centered content with a sticky element.

Thank you for reading.