Reputation: 5523
I'm trying to align a <form>
to be centered in a <div>
. This is what I've done till now:
<div style="height:auto; margin: 0 auto; align:center;">
<form style="width:50%; margin:0 auto;" onSubmit="return false;">
</form>
</div>
This centers the form, but is there any other way to do this on a more professional way?
I also have a button in this form which is aligned left by default. I tried to change the alignment but it failed.
Who can help me?
Upvotes: 2
Views: 34183
Reputation: 98718
[is] there any other way to be more professional?
<div style="height:auto; margin: 0 auto; align:center;">
Nobody else mentioned this error, but align
is not a CSS property.
Perhaps you meant align
as a <div>
attribute...
<div align="center">
However, that's been deprecated, so centering horizontally within a <div>
would be properly done with text-align
...
<div style="text-align: center;">
Upvotes: 1
Reputation: 34855
Simplest way is to remove the CSS from the HTML and remove the align:center
.
That way the button
aligns naturally to the left.
div{
height:auto;
margin:0 auto;
border:1px solid blue;
}
form{
border:1px solid red;
width:50%;
margin:0 auto;
}
HTML
<div>
<form>
<button></button>
</form>
</div>
Example: http://jsfiddle.net/kCt7k/
EDIT:
I need the button to be centered.
Sorry, misread that in the original Q.
In that case, you can use text-align:center
form{
border:1px solid red;
width:50%;
margin:0 auto;
text-align:center;
}
Example 2: http://jsfiddle.net/kCt7k/1/
However, this may mess with the other elements in the form.
You could just set the button
as a block
element and apply margins to it.
button{
width:100px;
display:block;
margin:0 auto;
}
Example 3: http://jsfiddle.net/kCt7k/2/
Upvotes: 18
Reputation: 2229
The css is fine, but IMO the "correct" way to do this would be through a separate css file. Same with the onsubmit that should be through seperate jquery or js. For the button issue I'd need to see the css from the style sheet and any inline css you are using. could be any number of reasons that something else is overriding the behavior you want.
One tip with css is if the element isn't behaving correctly, put a 1px solid colored border around it and then you can see where it is being rendered in the browser. You can then put borders around the other items and see where things are overlapping or pushing an element out of the position you want.
Upvotes: 0
Reputation: 67193
Being "more professional" might entail moving your style attributes to a separate CSS file. Other than that, this seems like a perfectly reasonable approach.
Would you like me to guess what you did with the button that is wrong?
Upvotes: 0