1

Hey I'm new to coding and here is my predicament. I didn't know how to vertically center elements in a div, and apparently this is a common problem because there isn't a simple class that does that function. So I looked around at a few methods and came up with the following solution to center the text within the container div.

CodePen:

http://codepen.io/mmartinb/pen/ozzjVN

The HTML:

  <div class="container" id="tryone">
<div id="trytwo">
 <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ita relinquet duas, de quibus etiam atque etiam consideret. Atque his de rebus et splendida est eorum et illustris oratio. Claudii libidini, qui tum erat summo ne imperio, dederetur. Eam si varietatem diceres, intellegerem, ut etiam non dicente te intellego; Sint ista Graecorum; Duo Reges: constructio interrete. Piso igitur hoc modo, vir optimus tuique, ut scis, amantissimus. At iam decimum annum in spelunca iacet. Sapientem locupletat ipsa natura, cuius divitias Epicurus parabiles esse docuit. Qui-vere falsone, quaerere mittimus-dicitur oculis se privasse;</p>
</div>
<img src="http://res.cloudinary.com/dqoqzoncd/image/upload/v1474214059/YzW4rUu_f69vph.jpg" alt="Manuel Martin" id="smaller-image"> 
</div>

The CSS:

#tryone{
  max-width:1000px;

}

#trytwo{ 
  top: 50%;
  max-width: 550px;
  float: left;
  margin-top: 45px;
}

Which was just adding a margin-top to the text div. The only issue is that the code does not seem very flexible. If I want to change the size of my text which I will end up wanting to, the the container will be unbalanced unless I change the margin-top:. Is there a solution such that a change in text doesn't unbalance the container.

manuel
  • 105
  • 10
  • Google is your friend... https://philipwalton.github.io/solved-by-flexbox/demos/vertical-centering/ – Anselm Sep 18 '16 at 21:48

2 Answers2

1

try this: (if u don't care about IE9)

#tryone{
  max-width:1000px;
  display: flex;
  align-items: center;
}
#trytwo{ 
  max-width: 550px;  
}
Marouen Mhiri
  • 1,640
  • 1
  • 14
  • 20
0

you can use flexbox in order to align items vertically. Flexbox has a property called align-items, you can check it out here: https://scotch.io/tutorials/a-visual-guide-to-css3-flexbox-properties

In order to achieve what you want, you'll need to add the following to the #tryone id styles:

#tryone{
   max-width:1000px;
   display:flex;
   align-items: center;
}

And remove from #trytwo (I've removed this since is no longer needed):

#trytwo{ 
    top: 50%;
    max-width: 550px;
    margin-top: 45px;
}

Here is a plunker with a working copy: https://plnkr.co/edit/5jOUuMPUv4a1gvDdNfgV?p=preview

Hope this helps!