How to prevent the scrolling of a given element?

Asked

Viewed 28 times

-3

I have a list of several items, the first being a <div>. I want this one <div> always be in the same position (visible at the top), regardless of whether the scroll bar moves up or down. See below for an example:

li {
    font-size: 25px;
}
<ul>
    <div>
        <input type="text" placeholder="Search"/>
    </div>
    <li>Item1</li>
    <li>Item2</li>
    <li>Item3</li>
    <li>Item4</li>
    <li>Item5</li>
    <li>Item6</li>
    <li>Item7</li>
</ul>

In this code above, I want the first item on the list (in case a <div>) do not move when the user moves the scroll bar down. How can I do this in CSS?

  • I’m not sure I understand, but maybe use position: sticky and top: 0 in div be the way to what you want

  • Why did I get downvote? How can I improve my question?

  • 2

    @Jeanextreme002 I can not speak for other people, but maybe [Edit] to put what tried and where had difficulty maybe help. First that has N ways to do, depends on the requirements. And another thing is that there is a "do for me" even if it was not purposeful.

1 answer

2


Remember that DIV should not go inside UL, and I really think you don’t even need to do this structure like this, see https://html.spec.whatwg.org/#the-ul-element:

Zero or more li and script-supporting Elements.

But it doesn’t even fit in the question something so opinionated

To resolve the issue of fixing on the screen use position: Fixed

ul > div {
    position: fixed;
}

ul {
    padding-top: 1px;
}

ul > li:first-of-type {
    margin-top: 32px;
}

li {
    font-size: 25px;
}
<ul>
    <div>
        <input type="text" placeholder="Search"/>
    </div>
    <li>Item1</li>
    <li>Item2</li>
    <li>Item3</li>
    <li>Item4</li>
    <li>Item5</li>
    <li>Item6</li>
    <li>Item7</li>
</ul>

Or position:Sticky

ul > div {
    position: sticky;
    top: 0; /*necessário para o sticky*/
}

li {
    font-size: 25px;
}
<ul>
    <div>
        <input type="text" placeholder="Search"/>
    </div>
    <li>Item1</li>
    <li>Item2</li>
    <li>Item3</li>
    <li>Item4</li>
    <li>Item5</li>
    <li>Item6</li>
    <li>Item7</li>
</ul>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.