Wanna see something cool? Check out Angular Spotify 🎧

CSS Layout - Horizontal & Vertical Align

In CSS, several properties can be used to align elements horizontally and vertically. I hope these below tips will help you understand and able to align the element center horizontal and vertical. Before going deeply, you can refer to these below source with good explanation and example.

Center Horizontal

1. Inline element (like text or button..)

To simply center text inside a block element is using: text-align: center

HTML

<div class="border-wrapper horizontal-inline-element-center">
  <p>
    Lorem Ipsum is simply dummy text of the printing and typesetting industry.
  </p>
  <button>Submit</button>
</div>

CSS

.horizontal-inline-element-center {
  text-align: center;
}

2. Block element (div)

To horizontally center a block element (like div), use margin: auto;

HTML

<div class="border-wrapper horizontal-block-element-center">
  <p>
    Lorem Ipsum is simply dummy text of the printing and typesetting industry.
  </p>
</div>

CSS

.horizontal-block-element-center {
  max-width: 40em;
  margin: 0 auto;
}

Center Vertical

3. Vertical Anything

This is a bit more tricky, but with position: absolute and transform: translate(0, -50%), we will be able to align center vertically, even if we don’t know its height. Translate negative 50% means move an element from its current position to middle of element’s height based on Y-axis

HTML

<div class="wrap-col">
  <div class="text-wrap">
    <h1>
      <a href="#">Pizza</a>
    </h1>
    <p>
      <a href="#"
        >Pizza is a flatbread generally topped with tomato sauce and cheese and
        baked in an oven</a
      >
    </p>
  </div>
  <div
    class="wrap-background backstretch"
    style="background-image: url(pizza.jpg)"
  ></div>
</div>

CSS

.wrap-col {
  float: left;
  width: 33.333333%;
  position: relative;
}

.wrap-col::before {
  position: absolute;
  content: '';
  height: 100%;
  width: 100%;
  z-index: 1;
  background: rgba(128, 128, 128, 0.4);
}

.wrap-background {
  min-height: 250px;
}

.text-wrap {
  position: absolute;
  top: 50%;
  transform: translate(0, -50%);
  width: 100%;
  z-index: 1;
  text-align: center;
}

.text-wrap a {
  color: #fff;
}
Published 17 Jun 2018

Read more

 — How we handle time zone and locale at Zyllem
 — The myth of the Genius Programmer
 — Angular Tips: Avoiding unnecessary RxJS in vendor.ts
 — Analyze webpack bundle with source-map-explorer. Optimize moment.js
 — Uncaught TypeError: Cannot read property 'name' of undefined