Centering with CSS

July 24, 2023


1. Use “line-height” for vertical centering in CSS

Demo 1:

  • Use case for button, menu. 

  • Set up the line height, the wording will be positioned vertically centered.

HTML
<div class="button">Click</div>
CSS
.button {
  width: 100px;
  height: 50px;
  line-height: 50px;
  background: #8dc4e3;
  color: #fff;
  text-align: center;
  border-radius: 8px;
  cursor: pointer;
}

Check on my codepen


Demo 2:

  • Use case for object centering.

  • Consider the text lines as objects; to position these lines as if they were objects, we need to apply the 'Inline-block' attribute.

HTML
<div class="box">
  <div class="box_content">
    <p>This is the demo wording.</p>
  </div>
</div>
CSS
.box {
  width: 500px;
  line-height: 200px;
  border: 3px solid #8dc4e3;
  text-align: center;
}

.box_content {
  display: inline-block;
  width: 300px;
  line-height: 40px;
  background: #8dc4e3;
  color: #fff;
}

Check on my codepen


2. Use “absolute” for vertical centering in CSS

Demo 1:

  • The absolute positioning is used with ‘top:50%’ to capture 50% of the space’s height.

  • The margin-top of the object to be centered is set to the negative half of its own height.
HTML
<div class="box">
  <div class="box_content">
    <p>This is the demo wording.</p>
  </div>
</div>
CSS
html {
  font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
  color:white;
}

.box{
  width: 500px;
  height: 250px;
  background: #8dc4e3;
  text-align: center;
  margin: 50px auto 0;
	position: relative;
  line-height: 40px;
}

.box_content{
	width: 300px;
  background: #02A6F0;
  height: 70px;
  position: absolute;
  top:50%;
  left: 50%;
  margin-left: -150px;  /* half of the width */
  margin-top: -35px; /* half of the height */
}

Check on my codepen