Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URLs added here will be added as <link>s in order, and before the CSS in the editor. You can use the CSS from another Pen by using its URL and the proper URL extension.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Auto Save

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <h1>Stacking elements within a specific area Vanilla JS</h1>

<section class="c-lead">
  <div class="c-lead__body">
    <div class="js-fixed-text__area">
      <div class="c-lead__item js-fixed-text__item-area">
        <p class="c-lead__text js-fixed-text__hidden" aria-hidden="true">
          吾輩は猫である。名前はまだ無い。<br>
          どこで生れたかとんと見当がつかぬ。
        </p>
        <p class="js-fixed-text__item">
          吾輩は猫である。名前はまだ無い。<br>
          どこで生れたかとんと見当がつかぬ。
        </p>
      </div>
      <div class="c-lead__item js-fixed-text__item-area">
        <p class="c-lead__text js-fixed-text__hidden" aria-hidden="true">
          何でも薄暗いじめじめした所でニャーニャー泣いていた事だけは記憶している。<br>
          吾輩はここで始めて人間というものを見た。
        </p>
        <p class="js-fixed-text__item">
          何でも薄暗いじめじめした所でニャーニャー泣いていた事だけは記憶している。<br>
          吾輩はここで始めて人間というものを見た。
        </p>
      </div>
      <div class="c-lead__item js-fixed-text__item-area">
        <p class="c-lead__text js-fixed-text__hidden" aria-hidden="true">
          しかもあとで聞くとそれは書生という人間中で<br>
          一番獰悪な種族であったそうだ。<br>
          この書生というのは時々我々を捕えて煮て食うという話である。
        </p>
        <p class="js-fixed-text__item">
          しかもあとで聞くとそれは書生という人間中で<br>
          一番獰悪な種族であったそうだ。<br>
          この書生というのは時々我々を捕えて煮て食うという話である。
        </p>
      </div>
    </div>
  </div>
</section>
              
            
!

CSS

              
                .js-fixed-text__item-area {
  position: relative;
}
.js-fixed-text__item {
  position: absolute;
  top: 0;
}
.js-fixed-text__item.is-fixed {
  position: fixed;
}
.js-fixed-text__hidden {
  opacity: 0;
  pointer-events: none;
}


/* テストページ設定 */
body {
  margin: 0;
  padding: 150px 0 200vh;
}
h1 {
  text-align: center;
  margin-bottom: 250px;
  font-size: 30px;
}
.c-lead {
  background-color: #f0f0f0;
}
.c-lead__body {
  max-width: 960px;
  padding: 0 50px 50px;
  margin: 0 auto;
  line-height: 2;
  font-size: 20px;
}
.c-lead__item:first-child .js-fixed-text__item:before {
  content: "";
  display: block;
  padding-top: 50px;
}
.c-lead__text:after {
  content: "";
  display: block;
  height: 60vh;
}
              
            
!

JS

              
                //指定エリア内に要素を追従させ積み重ねる関数
const areaFixedText = () => {
	//エリアチェック
	const areas = document.querySelectorAll('.js-fixed-text__area');
	if(areas.length === 0) {
		return;
	}

	//追従チェック関数
	const checkFixed = (targets,area) => {
		//ブロックごとの高さを取得
		const height = [];
		targets.forEach(target => {
			target.style.paddingTop = '';
			target.style.paddingBottom = '';
			height.push(target.offsetHeight);
		});
		const heightLen = height.length;

		//追従エリアの情報を取得
		const areaPosi = area.getBoundingClientRect().top;
		const areaHeight = area.clientHeight;
		//追従の終了ポイント
		const endPosi = areaPosi + areaHeight;

		//ブロックごとの処理
		targets.forEach((target, index) => {
			//ブロックのtop位置設定
			let topHeight = 0;
			if(index === 1) {
				topHeight = height[0];

			} else if(index > 1) {
				topHeight = height.slice(0,index);
				topHeight = topHeight.reduce((a, x) => a + x);
			}
			target.style.paddingTop = topHeight + 'px';

			//ブロックのbottom位置設定
			let bottomHeight = 0;
			if(index !== heightLen - 1) {
				bottomHeight = height.slice(index+1,heightLen);
				bottomHeight = bottomHeight.reduce((a, x) => a + x);
				target.style.paddingBottom = bottomHeight + 'px';
			}

			//要素の位置と高さを取得
			let targetHeight = target.clientHeight;
			const parent = target.parentNode;
			const parentPosi = parent.getBoundingClientRect().top;
			const startPosi = parent.getBoundingClientRect().top;
			parent.style.height = '';
			const parentHeight = parent.clientHeight;
			if(targetHeight > parentHeight) {
				parent.style.height = targetHeight + 'px';
			}

			//エリア内の処理
			if(0 > startPosi && targetHeight < endPosi) {
				target.classList.add('is-fixed');
				target.style.top = '';

			//エリアより上の処理
			} else if(0 <= startPosi) {
				target.classList.remove('is-fixed');
				target.style.top = '';

			//エリアより下の処理
			} else {
				target.classList.remove('is-fixed');

				//停止位置を設定
				topHeight = 0;
				if(index < heightLen - 1) {
					topHeight = height.slice(index + 1,heightLen);
					topHeight = topHeight.reduce((a, x) => a + x);
				}
				target.style.top = (areaHeight - ((-areaPosi) - (-parentPosi)) - targetHeight + bottomHeight - topHeight) + 'px';
			}
		});
	}


	//エリアごとに処理
	areas.forEach(area => {
		//エリア内に追従要素が存在する場合のみ処理する
		const targets = area.querySelectorAll('.js-fixed-text__item');
		if(targets.length > 0) {
			/*
				要素が画面内に入ったら処理
			*/
			const listener = {
				handleEvent: () => {
					checkFixed(targets,area);
				}
			};
			const observer = new IntersectionObserver(entries => {
				entries.forEach(entry => {
					if(entry.isIntersecting) {
						//画面に表示されているエリアのみスクロールイベント発火
						window.addEventListener('scroll', listener, {passive: true});

					} else {
						//画面外のときはスクロールイベント削除
						window.removeEventListener('scroll', listener, {passive: true});
					}
				});
			});
			//observer監視開始
			observer.observe(area);

			/*
				レスポンシブ対応
			*/
			//表示エリアリサイズ監視 ResizeObserver
			const resizeObserver = new ResizeObserver(() => {
				checkFixed(targets,area);
			});
			//リサイズ監視開始
			resizeObserver.observe(area);
		}
	});
}
areaFixedText();
              
            
!
999px

Console