DEV Community

Cover image for How To Create A Resizing Header With Plain CSS
Julia 👩🏻‍💻 GDE
Julia 👩🏻‍💻 GDE

Posted on

How To Create A Resizing Header With Plain CSS

For my projects I want to use as much CSS and as little JavaScript as possible (for accessibility reasons).

That's why I was looking for a way to resize the header when scrolling with simple CSS.

Demo from website YurisCodingClub - tips on how to get into tech as a career switchers at any stage.

Here's what I found.

The Code

The project was built using Next and TypeScript.

To achieve the resizing effect, we need to create an outer and an inner container in HTML - shown here as <header className"header-outer"> and <div "header-inner">.


Here is the HTML code to create the header.

<header className="header-outer">
  <div className="header-inner">
    <Link href="/">
      <div className="logo-container">
        <a className="logo" aria-label="back to home">
    <Navbar />
Enter fullscreen mode Exit fullscreen mode


Here is the CSS code for styling the header.

To create the effect, we have to work with different heights and top positions for each container.

Both the outer and the inner container must have position: sticky. The height of the outer container is greater than that of the inner container by how much the position on top is less. You can use the height you are aiming for.

.header-outer {
  align-items: center;
  background: white;
  box-shadow: 0 6px 20px 0 rgba(0, 0, 0, 0.1);
  display: flex;
  /* set the height for the header at its max height you want */
  height: 150px;
  left: 0;
  padding: 0 50px;
  position: sticky;
  /** set the value of `top` with the difference between
  * the height of the outer and inner container to compensate
  * for this */
  top: -50px;
  width: 100%;
  z-index: 1;

.header-inner {
  align-items: center;
  background: white;
  display: flex;
  /** specify the height of the header that you want when scrolling 
  *The difference between this height and the height of the outer header
  *is the value of the `top` of the outer container */
  height: 100px;
  justify-content: space-between;
  left: 0;
  position: sticky;
  top: 0;
  width: 100%;
Enter fullscreen mode Exit fullscreen mode

That's it.

Now, when scrolling, the sticky position of the outer container starts outside the screen by 50 (because of the negative value top: -50px), while now the inner container sticks at the height you aim for.


There are so many great things you can do with just CSS. You just have to be a little creative and willing to find a solution for using plain CSS.

If you have other suggestions, I'd love it if you could share them in the comments below.

Thank you

Thanks for your reading and time. I really appreciate it!

Top comments (0)