center horizontal div css code example

Example 1: center div horizontally and vertically

.parent {
  position: relative;
}
.child {
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
}

Example 2: css align items vertical center

.parent {
  display: flex;
  justify-content: center;
  align-items: center;
}

Example 3: css align center vertical and horizontal

.parent-class {
  display: flex;
  align-items: center;
  justify-content: space-around;
}

Example 4: how to horizontal center a div in css

#inner {
  width: 50%;
  margin: 0 auto;
}

Example 5: css center div

<!-- 
	 Simple CSS CENTER DIV Example
 	 
	 * See Fiddle in link for PoC *
-->

<div class="parent">
  <div class="child">
    <p>
      Eh Up Me Duck!
    </p>
  </div>
</div>

<style>
.parent {
  /* Just for aesthetics: see fiddle */
  border: 1px solid black;
  padding: 2px;
}

.child {
  border: 1px solid red;
  width: 50%;
  
  /* This is where the magic happens */
  margin-left: auto;
  margin-right: auto;
  /**********************************/
}

p {
  /* As you do */
  text-align: center;
}
</style>

Tags:

Html Example