Reputation: 337
I am learning HTML and not able to align my HTML form in the center of the web page. Kindly help me resolve the issue. The HTML code is as follows:
<body>
<div style="border: 1px solid black; width: 400px; text-align: center;"
align="center">
<form >
<!-- some code -->
</form>
</div>
</body>
Upvotes: 0
Views: 1533
Reputation: 69
at first set width property to absolute unit(px, cm etc) or relative unit(rem, em, %) then use margin-left:auto; and margin-right:auto;
Why this work ? Because after you set the width of block level element browser(user-agent) can make calculation, i.e. assign exact value to auto
placeholders such as:
freeSpace = parentElementWidth - childBlockLevelElementWidth;
auto = freeSpace/2;
Upvotes: 0
Reputation: 15657
<body style='border: 2px solid black;'>
<form style='border: 2px solid red;width:50%;margin:0 auto;text-align:center'>
<!-- some code -->
<input type='text'>
</form>
</body>
Upvotes: 0
Reputation: 358
Also you can do like this inside form tag specify style="padding-left:200px" but thats not a good way while designing a website
Upvotes: 0
Reputation: 358
Remove align center from div tag and use center tag before form and close it after form .If it is not working do a reply.FYI don't use div width in pixels please use it in percentage like 100% .If u use in pixels u may face problems when u switch to other devices like mobile to desktop ...
Upvotes: 1
Reputation: 10975
To achieve expected result, use below option of flex items
Below mentioned will center the content vertically and horizontally
align-items: center; // align-items will center content horizontally
justify-content: center;// justify-content will center content vertically
Note: To make justify content vertically center, define html and body full screen height 100%, as by default html,body height is auto which will not cover entire screen
CSS:
html, body{
height:100%;
}
body{
display:flex;
align-items: center;
justify-content: center;
height:100%;
}
Codepen for reference - https://codepen.io/nagasai/pen/JJrPRM
Upvotes: 0
Reputation: 372
Add margin: auto;
to your parent div style. text-align
and align
are not necessary there. Text-alignment will affect the alignment of your inner text not the container you are setting it too.
If you are trying to center a element with a known width then you should be using margin: 0 auto;.
If you are trying to center the content of an element (text, images etc.) then you should be using text-align: center.
Although it's possible to center block elements with text-align: center by settings it's display to inline (or inline-block) and using text-align: center on the container you probably shouldn't.
Check this link too to learn more about how margin works CSS Margins
Upvotes: 2