absoluteを使わず要素の真ん中に配置する方法

目次

デモ

RYUKYU

解説

gridでposition:absoluteを使わずに要素を真ん中に配置する方法を紹介します。

親要素にdisplay:gridを指定し、2つの小要素をgridで同じ位置に重ねます。 小要素全てに以下を指定すると小要素を重ねることが可能です。

grid-row: 1 で両方の要素を1行目に配置します。

grid-column: 1 / -1 で1列目から最後の列までを指定します。

重ね順で一番上にしたい要素をz-indexで指定します。

小要素を上下中央寄せする場合はplace-self-center で要素を真ん中に配置します。

全体のコード

<div class="grid grid-rows-1">
  <div class="relative z-10 col-span-full place-self-center text-[15cqw] tracking-wider text-white mix-blend-exclusion transition-all duration-300 [grid-row:1]">
      RYUKYU
  </div>
  <div class="col-span-full [grid-row:1]">
    <video
    class="aspect-video h-full w-full"
    preload="auto"
    loop
    autoplay
    muted
    >
      <source src="/sample.mp4" type="video/mp4"/>
    </video>
  </div>
</div>