I have tried to center this vertically in body
(not horizontally). Also, I do not want to specify heights or anything like that. I tried adding a wrapper with a 100% height and other things, but got nowhere. Can you please help me fix this?
jsFiddle Here
<form name="signup" class="signup" action="signup.php" style="border: 1px solid #000; "> <input type="text" placeholder="Email"/><br> <input type="text" placeholder="Username"/><br> <input type="password" placeholder="Password"/><br> <button type="submit">Next</button> </form>
when it comes to heighs the fast answer is always "you can't". Html pages are intended to be vertically scrolled and heights should be free to change according to the content. So there's no proper way to center your div vertically with css and html.
right are positioned absolutely with top: 50% and use margin-top: -0.8em to get vertical centering (use one-half of line-height value). Use the left and right offsets (or padding) to adjust the child elements horizontal position as needed.
For vertical alignment, set the parent element's width / height to 100% and add display: table . Then for the child element, change the display to table-cell and add vertical-align: middle . For horizontal centering, you could either add text-align: center to center the text and any other inline children elements.
If you want to vertically centre a div for all browsers the best solution is to build vertically and horizontally centre a fixed-width, flexible height content box. It works for all recent versions of Firefox, Opera, Chrome, and Safari.
See this edited version of your jsFiddle.
Basically, just wrap your content in <div class = "main"><div class = "wrapper"></div></div>
, and add the following CSS:
html, body { height: 100%; } .main { height: 100%; width: 100%; display: table; } .wrapper { display: table-cell; height: 100%; vertical-align: middle; }
If you have flexbox available, you can do it without using display: table;
Code example:
html, body { height: 100%; width: 100%; } .container { align-items: center; display: flex; justify-content: center; height: 100%; width: 100%; }
<html> <body> <div class="container"> <div class="content"> This div will be centered </div> </div> </body> </html>
Ta-da! Vertically and horizontally centered content div. JSFiddle: https://jsfiddle.net/z0g0htm5/.
Taken mostly from https://philipwalton.github.io/solved-by-flexbox/demos/vertical-centering/ and https://css-tricks.com/snippets/css/a-guide-to-flexbox/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With