- This topic is empty.
-
AuthorPosts
-
January 15, 2012 at 4:25 am #9178David HoangKeymaster
I have a
<div>
element which contains text and I want to align the contents of this<div>
vertically center.Here is my
<div>
style:#box { height: 170px; width: 270px; background: #000; font-size: 48px; color: #FFF; text-align: center; }
<div id="box"> Lorem ipsum dolor sit </div>
What is the best way to achieve this goal?
September 2, 2014 at 9:10 am #9179David HoangKeymasterA better, easier, responsive approach is to set
margin-top
in CSS to around 45%:margin-top: 45%;
You might have to play with that number, but it will be in the center of the surrounding div.
March 15, 2015 at 1:56 am #9182David HoangKeymaster.element{position: relative;top: 50%;transform: translateY(-50%);}
Add this small code in the CSS property of your element. It is awesome. Try it!
September 19, 2015 at 12:38 pm #9183David HoangKeymasterNewer browsers now support the CSS
calc
function. If you are targeting these browsers you may want to look into doing something like this:<div style="position: relative; width: 400px; height: 400px; background-color: red"> <span style="position: absolute; line-height: 40px; height: 80px; text-align: center; width: 300px; overflow: hidden; top: calc(50% - 40px); left: calc(50% - 150px);"> Here are two lines that will be centered even if the parent div changes size. </span> </div>
The key is to use
style = "top: calc(50% - [innerFixedHeightInPX/2]px); height: [innerFixedHeightInPX]px;"
inside an absolute or relatively positioned parent div.August 10, 2016 at 7:42 am #9180David HoangKeymasterThis works perfectly.
You have to use table style for the div and center align for the content.
September 5, 2016 at 12:39 pm #9181David HoangKeymaster.text{ background: #ccc; position: relative; float: left; text-align: center; width: 400px; line-height: 80px; font-size: 24px; color: #000; float: left; }
March 17, 2017 at 12:00 pm #9184David HoangKeymaster<!DOCTYPE html> <html> <head> <style> .main{ height:450px; background:#f8f8f8; display: -ms-flexbox; display: -webkit-flex; display: flex; -ms-flex-align: center; -webkit-box-align: center; align-items: center; justify-content: center; width: 100%; } </style> </head> <body> <div class="main"> <h1>Hello</h1> </div> </body> </html>
September 22, 2017 at 7:56 am #9185David HoangKeymaster.box { width: 100%; background: #000; font-size: 48px; color: #FFF; text-align: center; } .height { line-height: 170px; height: 170px; } .transform { height: 170px; position: relative; } .transform p { margin: 0; position: absolute; top: 50%; left: 50%; -ms-transform: translate(-50%, -50%); transform: translate(-50%, -50%); }
<h4>Using Height</h4> <div class="box height"> Lorem ipsum dolor sit </div> <hr /> <h4>Using Transform</h4> <div class="box transform"> <p>Lorem ipsum dolor sit</p> </div>
-
AuthorPosts
- You must be logged in to reply to this topic.