The sticky position is failing to function properly when I set the float property to the left on other

I noticed that the position sticky for the header stops working once I add float:left to another element. The tricky part is, if I remove the float:left from main>div, the sticky header works fine. Despite my efforts to find a solution through Google, no luck so far. Below is the code snippet:

<!doctype html>
<html lang="en">

<head>
    <style>
        .header {
            height: 100px;
            position: sticky;
            top: 0;
            width: 100%;
            background-color: pink;
        }

        main>div {
            float: left;
            /*If I don't use it, the sticky header works*/
            height: 1500px
        }

        .first {
            background: linear-gradient(to top, red, yellow);
            width: 300px;
            top: 0;
        }

        .second {
            background: linear-gradient(to top, khaki, gray);
            width: calc(100% - 600px);
        }

        .third {
            background: linear-gradient(to top, tomato, green);
            width: 300px;
        }
    </style>
</head>

<body>
    <header class="header">
        sticky header
    </header>
    <main>
        <div class="first"></div>
        <div class="second"></div>
        <div class="third"></div>
    </main>

</body>

</html>

You can view and test the same code on Jsfiddle here.

Answer №1

Whenever you create a “float” element, it is essential to clear it afterwards.

To achieve this, consider inserting the following line below:

    <div style="clear:both;"></div>

By including the above code snippet, your final result will look like the example provided below. Don’t hesitate to move the styling to an external class if needed.

    <header class="header">
    sticky header
</header>
<main>
    <div class="first"></div>
    <div class="second"></div>
    <div class="third"></div>
</main>
<div style="clear:both;"></div>
You can also utilize a pseudo-element (such as "after" in CSS) to accomplish the same effect [here](https://www.w3schools.com/cssref/sel_after.asp).

Answer №2

If you are designing a layout, it's advisable to utilize the -x-sticky property for cross-browser compatibility and set your column widths in percentages to ensure responsiveness.

For instance, execute the code snippet below:

body{
   box-sizing: border-box;
   padding: 0;
   margin: 0;
}
header {
   height: 60px;
   width: 100%;
   background-color: pink;
   position: -webkit-sticky;
   position: -ms-sticky;
   position: -moz-sticky;
   position: -o-sticky;
   position: sticky;
   top: 0px;
   z-index: 1;
}
main {
   display: flex;
   width: 100%;
   height: 1500px;
}
.first {
   background: linear-gradient(to top, red, yellow);
   min-width: 20%;
}
.second {
   background: linear-gradient(to top, khaki, gray);
   flex-grow: 1;
}
.third {
   background: linear-gradient(to top, tomato, green);
   min-width: 20%;
}
   <header>
      sticky header
   </header>
   <main>
      <div class="first"></div>
      <div class="second"><p>Lorem ipsum dolor sit amet consectetur adipiscing elit, vitae tincidunt nascetur donec porttitor aenean et nunc, ut dictum inceptos facilisis commodo cum. Duis magnis parturient sollicitudin diam augue placerat imperdiet neque, euismod cum nostra erat lacus et conubia, facilisi pellentesque molestie risus mus dapibus vel. Malesuada vestibulum habitasse class sodales viverra mauris fermentum tortor massa bibendum augue libero, euismod montes sed dis magna vel leo praesent mattis platea eleifend. Neque commodo maecenas odio curae cubilia potenti habitant congue porttitor, integer libero mattis nisl sed mauris donec litora magnis, nulla dignissim platea hac dui varius tellus tincidunt.</p> <p>Dignissim proin arcu magna vitae id nam volutpat natoque semper sem, aliquet erat aliquam sociosqu scelerisque eget urna mollis sagittis. Posuere arcu sociosqu mi ad lacinia vitae ac nascetur tempor pharetra aptent fringilla, turpis sodales himenaeos malesuada mattis nisl diam sapien quisque cum. Enim dictum etiam mollis egestas et magna blandit dignissim, ullamcorper parturient odio suspendisse curabitur habitasse dui facilisi, laoreet ridiculus est ad vehicula curae nullam.</p> <p>Facilisis odio mauris consequat mattis faucibus aliquam eu semper condimentum, imperdiet natoque magna leo malesuada lacinia posuere placerat tellus, suscipit dapibus pharetra porta eros diam feugiat dictum. Suscipit euismod fermentum interdum bibendum nullam porttitor, pharetra dis mollis vivamus leo elementum commodo, facilisi rhoncus aptent ligula maecenas. Sodales pellentesque purus parturient mollis mauris tellus id vehicula, velit ac quam sociosqu molestie sollicitudin neque eleifend, mus porttitor aenean penatibus libero fringilla sagittis.</p> <p>Phasellus ornare eros per nam sollicitudin taciti himenaeos, senectus auctor fusce varius magna hendrerit. Urna proin lacus conubia tortor venenatis mauris nec facilisi, fringilla arcu non accumsan pellentesque neque ut dictum euismod, curae tempor eu felis habitasse mi dui. Viverra vehicula ultrices etiam maecenas fusce pulvinar dis sem litora, luctus molestie suscipit tristique imperdiet gravida pretium augue, vel velit nibh hac mus nam consequat eros.</p> <p>Metus feugiat nisl felis fames condimentum facilisi posuere tempus ultricies scelerisque porttitor aptent, justo tempor magnis ultrices phasellus cras nascetur interdum augue aenean iaculis. Lacinia diam lectus lacus facilisis nisl accumsan magna curae nullam placerat bibendum dictum, vehicula dui integer non viverra iaculis interdum vitae at suscipit egestas. Ac aptent fermentum netus eros vulputate phasellus iaculis, cum inceptos velit suspendisse morbi viverra, ante fringilla faucibus donec placerat nullam. Aliquam diam integer vivamus ligula nam cras cursus tristique libero, mattis nisi vestibulum litora enim suspendisse inceptos fames facilisi, erat penatibus ridiculus taciti duis bibendum tortor ornare.</p> <p>Lectus dui sagittis et nascetur nec hendrerit convallis, dapibus curabitur fermentum varius scelerisque nullam platea, metus elementum mattis id semper dignissim. Ridiculus habitasse at sociosqu gravida dui metus velit aptent praesent, dapibus purus egestas et diam nisi pulvinar porttitor, ullamcorper hac integer cubilia sagittis lobortis justo tristique. Penatibus diam convallis velit sapien, ornare nascetur morbi laoreet vulputate, vitae lectus potenti.</p> <p>Egestas nostra mus montes suscipit morbi mattis vestibulum, sapien penatibus laoreet luctus eu feugiat. Integer a fringilla aenean quisque diam nostra, nisl volutpat commodo augue gravida massa, praesent elementum pulvinar curabitur proin.</p></div>
      <div class="third"></div>
   </main>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can I align a mapped button to appear on the opposite side of the data using Tailwind CSS?

I've been struggling to find a straightforward solution to this issue for a while now. Let me break it down - I need to display some data on the left side of a post card component with a button located right next to it. Here's an illustration: ...

presenting JSON data in a table format accurately

I recently created an ajax function that sends a get request to an API and retrieves JSON data, which I then display in a table. Here is what I have attempted: <script> function getInfo() { $.ajax({ type: "GET", url: "http: ...

CSS following a clicked event

http://codepen.io/anon/pen/GqmEAq My goal is to make the 'x' button clicked (the 'x' is created after clicking the plus sign on the menu) and then bring the dropdown back up. I have attempted: a:after:checked ~ .submenu{ max-height ...

Hyperlinks are being loaded

I recently noticed that my website was loading very slowly because I had quoted Wikipedia and included a direct link to the article. The link code looked like this: <a href="<?php echo $data['link']; ?>" target="_blank"><?php echo ...

How come my database is not receiving the data from the first name field?

I have encountered an issue with my comment form where the first name field data is not getting sent to the database along with the comments. I have already checked that the 'first_name' column exists in the database, but still facing this proble ...

css scroll-snap: highlighting the snapped element

I created a horizontal grid containing multiple cards that scroll smoothly using CSS scroll-snap functionality when navigated with a mouse or touchscreen. The issue arises when attempting to navigate the grid using a keyboard. After moving through the gri ...

What could be causing my carousel to malfunction?

Can someone assist me, please? I am having an issue where the carousel displays on the page, but the images are not showing and the buttons do not work. Please refer to the CSS + HTML snippet below: #my-carousel .carousel-inner .item { width: 100%; ...

"Include the 'unsafe' prefix at the start of the URL in AngularJS

Whenever I attempt to access app://csttree?featuretype=cst_issue&verticalid=2132321&l1=3213&l2=3242 within my app, the URL gets parsed as ==> unsafe:app://csttree?featuretype=cst_issue&verticalid=2132321&l1=3213&l2=3242 Is ...

The dropdown menu vanishes from sight as soon as the cursor moves away from a link

Recently, I encountered an issue while trying to create a dropdown menu using Jquery. The problem arose when attempting to select the second link, as the entire menu would disappear. Additionally, is there a way to ensure that only one dropdown menu is vis ...

Tips for resetting form fields and clearing previous values before resubmitting the form, allowing for a fresh start with empty fields

Welcome to my website! If you visit , you'll notice a feature I've added that clears form field values after submission. However, I'm encountering an issue where the fields remain filled when revisiting the page for another appointment. I at ...

Retrieve the ID of the image element using Jquery from a collection of images within a div container

I'm encountering a simple issue that I can't seem to solve. I am working on a basic slider/gallery with the following functionalities: 1) "If button 1 is clicked, image one will appear." 2) "Clicking on button 2 will make IMAGE 1 slide left and I ...

Troubleshooting the unresponsive nature of the multi-level menu

I have incorporated a specific plugin into my application Check out my application here To access the menu, click on the third green button followed by any yellow button on the right side. However, the menu appears underneath another div rendering it unc ...

Adjust the height of the div container and implement a vertical scroll feature on the fixed element

I created a fiddle and was hoping to enable scrolling, but I have been unable to find a solution. http://jsfiddle.net/sq181h3h/3/ I tried both of these options, but nothing seems to be working: #league_chat { overflow-y:scroll; } #league_chat { ...

What steps are involved in linking Java with JavaScript?

After attempting to connect html and javascript using applet, unfortunately it was unsuccessful. I am curious if there is an alternative method besides applet to establish this connection. ...

Issue with Javascript functionality not persisting after page reload initiated with a href = '#'

I am facing an issue with a button on my webpage that is meant to redirect and reload the home page. However, after redirection to '#', my JavaScript seems to stop functioning correctly. Currently, my JavaScript code is enclosed within window.on ...

Is there a way to choose a div in Jsoup that lacks an id or any attributes?

I am facing a challenge where I have to choose a specific div using Jsoup. Traditionally, divs can be selected based on their id or class attributes using getElementById() for IDs and getElementsByClass() for classes. However, the div that I need to select ...

What's the reason for the element not inheriting margins from its parent?

I am facing an issue with centering an h1 header within a .banner element. When I try to apply margin to the header, it appears to indent not from the top border of the banner, but rather from the nav element located above the banner. After inspecting the ...

What is the best way to update a div element without the need for double clicking?

Let me explain this clearly. Currently, I have a table displaying in HTML when called. However, I want the table to disappear and show filtered results when someone enters a president's name and clicks on "Search for Presidents". I attempted using a c ...

Dynamic table that collapses/expands in Python's Flask framework

I am currently working on developing a table in Flask with collapsible rows. I have encountered an issue where, while hardcoding values works perfectly, populating the table using a loop with data from a Python dictionary results in only the first child of ...

Issue encountered while appending new rows to the tbody of a table

I'm encountering an issue with the append function within a for loop in my code. The string being passed to the function isn't parsing correctly and results in an error. How can I go about resolving this problem? Thanks! function getDetailPopUp ...