Languages

CSS - how to set position absolute with scrolling?

0 points
Asked by:
Paris-Bateman
504

How can I make absolute position for children elements and enable parent scrolling?

When I do such thing all the children elements stay in one place or they overlap.

My code:

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
<head>
  <style>

    .parent {
        width: 200px;
        height: 50px;
        margin: 5px;
        background: yellow;
    }

    .child {
        background: orange;
        position: absolute;
        top: 10px;
    }

  </style>
</head>
<body style="height: 50px">
  <div class="parent">
    <div class="child">some text here...</div>
  </div>
  <div class="parent">
    <div class="child">some text here...</div>
  </div>
  <div class="parent">
    <div class="child">some text here...</div>
  </div>
</body>
</html>

All I want to do is to have the 3 .parent elements with .child elements inside positioned 10px from the top but I need to enable scrolling and not destroy my page.

1 answer
0 points
Answered by:
Paris-Bateman
504

When you use position: absolute for child element, you need to add position: relative to the parent.

Practical example

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
<head>
  <style>

    .parent {
        width: 200px;
        height: 50px;
        margin: 5px;
        background: yellow;
        position: relative; /*  <----- required   */
    }

    .child {
        background: orange;
        position: absolute;
        top: 10px;
    }

  </style>
</head>
<body style="height: 50px">
  <div class="parent">
    <div class="child">some text here...</div>
  </div>
  <div class="parent">
    <div class="child">some text here...</div>
  </div>
  <div class="parent">
    <div class="child">some text here...</div>
  </div>
</body>
</html>

 

References

  1. position - CSS: Cascading Style Sheets | MDN
0 comments Add comment
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join