如何将粘性定位元素移出父div?

时间:2017-12-28 11:37:01

标签: html css position sticky

我想将position: sticky元素移动到父元素的最右边,然后再移出元素。就像在这张图片中一样:

enter image description here

但不知道该怎么做。我知道我可以通过position: absolute实现这一目标(我做了截图。)

CSS

h1 {
  position:-webkit-sticky;
  position: sticky;
  top: 10px;
  left: 100%;

HTML

<div>
    <p>Apparat</p>
    <p>Arcade Fire</p>
    <p>Same</p>
    <h1>Andrew W.K.</h1>
    <p>At The Drive-In</p>
    <p>Same`</p>
    <p>Chromeo</p>
    <p>Common</p>
    ....

我尝试了left: 110%px值,但没有效果。到目前为止我得到了什么:

enter image description here

我正在使用的codepen:https://codepen.io/asim-coder/pen/QapgYO

1 个答案:

答案 0 :(得分:2)

就像评论中提到的那样,只需对float: right;使用h1,然后使用减值执行一些margin-right

h1 {
  position: -webkit-sticky;
  position: sticky;
  top: 10px;
  /* left: 100%; No need of this anymore */
  /* Other styles   */
  background: green;
  color: white;
  line-height: 2em;
  margin: 0 -100px 0 0; /* Changed to -100px right and 0 on the other sides*/
  padding: 5px;
  display: inline-block;
  float: right;
}


/* Other styles */

* {
  box-sizing: border-box;
}

body {
  font: bold 18px/21px Helvetica, Arial, sans-serif;
}

p {
  font-weight: normal;
  background: orange;
  padding: .8em;
  margin: 0;
}

div {
  width: 500px;
  margin: auto;
  border: 1px solid orange;
  position: relative;
}
<div>
  <p>Apparat</p>
  <p>Arcade Fire</p>
  <p>Same</p>
  <h1>Andrew W.K.</h1>
  <p>At The Drive-In</p>
  <p>Same`</p>
  <p>Chromeo</p>
  <p>Common</p>
  <p>Converge</p>
  <p>Crystal Castles</p>
  <p>Same`</p>
  <p>Ted Leo & The Pharmacists</p>
  <p>T-Pain</p>
  <p>Chromeo</p>
  <p>Common</p>
  <p>Converge</p>
  <p>Crystal Castles</p>
  <p>Same`</p>
  <p>Ted Leo & The Pharmacists</p>
  <p>T-Pain</p>
  <p>Thrice</p>
  <p>TV On The Radio</p </div>