transform titles translate 50% H+V

by ian_smithz

HTML

<p>
Horizontally and vertically aligning text without 'text-align:center'.
</p>

<p>
For when you have to try... <em>too hard</em>.
</p>

<p>
Bunged a responsive image in, just for the hell of it! Choose your z-index as you wish.
</p>

<section class="fancypants-banner">

  <h1>H1 - H aligned with transform X</h1>

  <h2>H2 - H + V aligned with transform X + Y</h2>
  
  <img src="https://via.placeholder.com/200x200" alt="">
  
</section>

<p>
Some good alignment techniques here: <a href="https://www.w3.org/Style/Examples/007/center.en.html">https://www.w3.org/Style/Examples/007/center.en.html</a>
</p>

CSS

.fancypants-banner {
  position: relative;
  
  /* if cemtred element is looking blurry on a half pixeluse this below */
  /* transform-style: preserve-3d; */
  
  /* demo purpose */
  height: 300px;
  border: 1px solid red;
  text-align: center;
  width: 80%;
  margin: 0 auto;
}

/* centre h1 horizontally -  */
.fancypants-banner h1 {
  position: absolute;
  top: 0;
  left: 50%;
  
  /*need this when aligning text */
  margin-right: -50%;
  
  transform: translate(-50%, 0);
  
  /* demo */
  border: 2px solid blue;
  margin-top: 0;
  margin-bottom: 0;
}

/* centre h2 horizontally + vertically  */
.fancypants-banner h2 {
  position: absolute;
  top: 50%;
  left: 50%;
  
  /*need this when aligning text */
  margin-right: -50%;
  
  transform: translate(-50%, -50%);
  
  /* demo */
  border: 2px solid yellow;
  margin-top: 0;
  margin-bottom: 0;
}

/* centre img horizontally */
.fancypants-banner img {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  
  /* demo */
  max-width: 100%;
  border: 2px solid green;
}