<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body style="padding: 20px;">
<div style="background-color: whitesmoke; width: 400px; position: relative; max-height: 200px; overflow: auto;">
<ul>
<li style="margin-bottom: 60px;">1</li>
<li style="margin-bottom: 60px;">1</li>
<li style="margin-bottom: 60px;">1</li>
</ul>
<!-- bottom: 20px; left: 20px; working! -->
<button style="position: sticky; bottom: 20px; left: 20px;">btn</button>
</div>
<div style="background-color: whitesmoke; width: 400px; position: relative; max-height: 200px; overflow: auto;">
<ul>
<li style="margin-bottom: 60px;">1</li>
<li style="margin-bottom: 60px;">1</li>
<li style="margin-bottom: 60px;">1</li>
</ul>
<!-- right: 20px; Not working 😢 (bottom: 20px; always working) -->
<button style="position: sticky; bottom: 20px; right: 20px;">btn</button>
</div>
</body>
</html>
Yon can see this code look like:
Test html
When parent is position: relative
, child is position: sticky
,
The left prop is working, but right prop is not…
Please let me know why, and How can I solve?
2
Answers
Not sure why it’s not working but you could use
left: 100%;
as a workaround to get the intended resultLike this:
Do not position the
button
. Create an element, for example, namedfooter
, and position it at the bottom so that multiple child elements, including thebutton
, can be placed in the fixed bottom bar. It is easy to align the elements within the box, and the best approach is to usedisplay: flex
, where child elements can be positioned in numerous ways. I would highlight one approach:flex-direction: row
(it will list the elements from left to right)flex-direction: row-reverse
(it will list the elements from right to left)See the example below:
So, following my example, I moved your
<style>
tags into CSS classes, allowing you to achieve the same result with less code. Then, I placed your<button>
element as a child within a<div>
. The<div>
is aligned at the bottom using the.box-footer
class with a sticky position. The<div>
itself remains 100% wide and receives some padding.For this
<div>
with the.box-footer
class, I specified that its children should be displayed withflex
styles. This allows me to use all the CSS properties associated withflex
.By default, if you need to align the button to the left, you wouldn’t need this, but it doesn’t hurt to have it.
If you want to align the element to the right, there are several ways to do it. Perhaps the simplest is to tell
flex
to list the items in reverse order usingflex-direction
(which I placed in a separate class,.right
, so that I can demonstrate both the left and right examples with the.box-footer
).