简体   繁体   中英

How do I horizontally center align a button?

I'm trying to customize a code that was pre-written, so I'm not a coding expert and need this explained to me in layman's terms. Basically, I'm trying to horizontally center align a subscribe button.

Here's my code below:

<div class="clear"><input type="submit" value="Subscribe" name="subscribe" id="mc-embedded-subscribe" class="button"></div>

The easiest way to horizontally center an element is to set its margin-left and margin-right to "auto" in your CSS.

For example, styling the element by id:

#mc-embedded-subscribe {
    margin-left: auto;
    margin-right: auto;
}

Or use margin to center elements with class of "button" horizontally, with no top or bottom margin:

input.button {
    margin: 0 auto;
}

AleshaOleg's inline style will work, too. (And it's probably the better way to go if you're not comfortable with CSS.

You have got many write answer but I want to add some more thing to make this happen

  1. You have to use "margin:0 auto" this will center align the element in its immediate container.

  2. Your container should have width more than the width of item you want to be centered and div normally takes 100% of width so you may not feel it center until you give it some width in % or px.

See this example. in this outer div has 100% width but its child div has only width required for button and is centered using margin: 0 auto.

http://jsfiddle.net/zud8g/

<div style="width:100%">
    <div style="margin:0 auto; width:75px;">
        <input type="submit" value="Subscribe" name="subscribe" id="mc-embedded-subscribe" class="button">
    </div>
</div>

Try this. This is the easiest way to horizontally center. The margin: 0 auto, auto detected where center now, and places div in the center of the page.

<div style="margin: 0 auto;" class="clear">
    <input type="submit" value="Subscribe" name="subscribe" id="mc-embedded-subscribe" class="button">
</div>

in css it should be

.clear {
   text-align:center;
}
.clear .button {
   margin:auto;
}

the margin:auto; isn't always necessary but in some more stubborn cases makes things center. Tables are one such instance that don't seem to align without margin:auto;. Also make sure your div width is larger than your button width.

Note that centering must happen in a parent div or p tag, not in the button itself

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM