Home > Back-end >  Align sticky element to right side of parent element
Align sticky element to right side of parent element

Time:08-08

I am trying to build a sticky toolbar, that is aligned to the right side. But I cant get it to be aligned to that side:

If I use float: right; the element beneath gets pulled up, if I use a parent container, that spans over the whole screen width and use justify-content: end; And the use z-index: 10; or so, screen at that parent element is blocked.

So how do I align that element to the right side most elegantly?

.container {
  background-color: cyan;
  height: 1000px;
}

.sticky-element {
  position: sticky;
  top: 20px;
}

.other-stuff {
  padding: 20px;
}
<div >
  <div >
    <button>Button 1</button>
    <button>Button 2</button>
  </div>
   <div >
    Some other stuff that is drawn up if float: right is applied on sticky-element.
    (But shouldn't)
   </div>
</div>

CodePudding user response:

You can set a width:max-content and a margin-left:auto on .sticky-element, like so:

.container {
  background-color: cyan;
  height: 1000px;
}

.sticky-element {
  position: sticky;
  top: 20px;
  width:max-content;
  margin-left:auto;
}

.other-stuff {
  padding: 20px;
}
<div >
  <div >
    <button>Button 1</button>
    <button>Button 2</button>
  </div>
   <div >
    Some other stuff that is drawn up if float: right is applied on sticky-element.
    (But shouldn't)
   </div>
</div>

CodePudding user response:

You could make the entire sticky content to be flex and aligned to the end to have the elements on the right.

.container {
  background-color: cyan;
  height: 1000px;
}

.sticky-element {
  position: sticky;
  top: 20px;
  display:flex;
  justify-content: flex-end;
}

.other-stuff {
  padding: 20px;
}
<div >
  <div >
    <button>Button 1</button>
    <button>Button 2</button>
  </div>
   <div >
    Some other stuff that is drawn up if float: right is applied on sticky-element.
    (But shouldn't)
   </div>
</div>

  • Related