1

CodePen

I want to align the both vertically and horizontally, the height and width of the container will be fixed regarding other extenal factors.

How do i do that?

I've tried using flex

display: flex;
justify-content: center;
flex-direction: column;

but it gets rid of my horizontal alignment

Hashem Qolami
  • 97,268
  • 26
  • 150
  • 164
Pontiacks
  • 1,118
  • 2
  • 13
  • 23
  • 1
    possible duplicate of [CSS: Vertically align div when no fixed size of the div is known](http://stackoverflow.com/questions/7206640/css-vertically-align-div-when-no-fixed-size-of-the-div-is-known) – Paulie_D Mar 27 '15 at 17:35

2 Answers2

2

Actually, there are multiple ways to achieve vertical alignment, here is one:

div {
  width: 300px;
  height: 150px;
  background-color: #ddd;
  text-align: center;
  font-size: 0;
}

div::before {
  content: "";
  display: inline-block;
  height: 100%;
  vertical-align: middle;
}

a {
  width: 100px;
  height:50px;
  background-color: #ff0000;
  display: inline-block;
  vertical-align: middle;  
  font-size: 16px
}
<div>
  <a href="#">Some Text</a>
</div>
Community
  • 1
  • 1
Hashem Qolami
  • 97,268
  • 26
  • 150
  • 164
  • Thank you! just before your reply I found the answer using position:relative; and position:absolute; – Pontiacks Mar 27 '15 at 17:40
  • @Pontiacks You're welcome. Yes, as I mentioned there are couple of ways, but I assumed you want to keep the element in normal flow as an `inline-block` element which is stated clearly in the title of the question. – Hashem Qolami Mar 27 '15 at 17:42
0

Found the solution!

On the div parent:

position:relative;

On the a child:

position: absolute;
top: 50%;
left: 50%;
margin-left: -half_its_width;
margin-top: -half_his_height;
Pontiacks
  • 1,118
  • 2
  • 13
  • 23