I have put some content and form inside the main
element. Here is the HTML:
<main>
<h1>My main content</h1>
<form action="/action_page.php" id="form">
<input type="email" id="email" name="email" placeholder="Enter your email address"><br><br>
<input type="submit" value="Submit">
</form>
</main>
with the following CSS:
main {
width: 800px;
margin: 0 auto;
}
<main>
<h1>My main content</h1>
<form action="/action_page.php" id="form">
<input type="email" id="email" name="email" placeholder="Enter your email address"><br><br>
<input type="submit" value="Submit">
</form>
</main>
However, the main
element is not centered exactly. What could be the reason?
3
Answers
Since the entire content takes 100% of the
main
width, centering things will look exactly like non-centering them. Therefore, you can achieve your goal by specifying a width for the contents of yourmain
in percent (I used 50%) and then specify amargin-left
formain
that will be half of the unused real-estate in width. (So, if you have chosen your content to be of 50%, then it’s a margin-left of (100 – 50) / 2 % = 25%. If, instead you have chosen a width of 80%, then it would be a margin-left of (100 – 80) / 2 % = 10%).Of course, this can still be improved, but applying further size and other styles to your elements, but this is a good start, I suppose.
If you add
outline: 1px solid #000
tomain
, you will understand why it’s not centered.The
main
element takes up 800px no matter how wide the children are so you will always have a lot of white-space to the right of the form.Change
width
tomax-width
and adddisplay: inline-block
to havemain
wrap around the widest child, but you will get another problem instead.The element wont center anymore, because you can only center using
margin: auto
on block elements. So add adiv.container
around the main elements width a max-width and center that instead.Just decrease the
width
to the width of theform
(main
‘s content). You can check it in the inspector. And change thewidth
tomax-width
, to make it responsive.