Centering Elements

In this lecture, we'll deepen our understanding of CSS positioning by introducing more advanced concepts. We'll explore how elements are centered vertically and horizontally.

Desired Outcomes

By the end of this lecture, you should be able to:

  • Understand how to position elements with precision using advanced techniques.
  • Center elements vertically and horizontally

Centering Block Level Elements Horizontally

If you have a block level element (like a div), and you want to center it horizontally, you can use auto margins. However, this requires the element to have a set width:

HTML

<div class="center-block">Centered block</div>

CSS

.center-block {
    border: 3px dashed powderblue;
    margin-left: auto;
    margin-right: auto;
    width: 50%; /* or any specific width */
}
Centering Elements Horizontally
Centering Elements Horizontally

If the element is not block level by default, you can set it’d display property to block like so:

.center-block {
    display: block;
}

Centering Elements Vertically

In order to center an element vertically, you will need to use positioning, like in the example below:

HTML

<fieldset class="relative-parent">
   <legend>
         Relative parent
   </legend>
   <div class="absolute-child">Absolute child</div>
</fieldset>

CSS

.relative-parent {
    position: relative;
    width: 100%;
    height: 160px;
    border: 3px dashed powderblue;
}

.absolute-child {   
    width: 160px;
    height: 100px;
    margin: 0 auto;
    position: absolute;
    top: 50%;
    left: 0;
    right: 0;
    transform: translateY(-50%);
    background-color: crimson;
}
Centering Elements Vertically
Centering Elements Vertically