How to place a button in the center of div of dynamic size

33,348

Solution 1

This achieves what you're looking for in a simple, succinct, way:

.button {
    display:block;
    margin: 0 auto;
}

Solution 2

You need to give the button a specific width and then you can use automatic margins

.button {
  display: block;
  margin: 0 auto;
}

http://fiddle.jshell.net/CrHyd/

Solution 3

There's more than one way to do this. I prefer using percentages like so:

input[type="submit"]{
    min-width:20%;
    max-width:20%;
    margin:0% 39% 0% 40%; //margin-right = 39% to stop errors
}

Other people prefer a margin:auto approach but personally I've never found this to work. Other methods include using floats but I don't agree with this property as it mis aligns other elements in some browsers.

Using top and left will cause errors as you've not specified a position type other than default (static).

Share:
33,348
s.mujahid8
Author by

s.mujahid8

Updated on July 09, 2022

Comments

  • s.mujahid8
    s.mujahid8 almost 2 years

    I have this code:

    <div class="outer">
        <ul class="list">
            <li class="inner">
                <div class="line">information1</div>
                <div class="line">hyperlink1</div>
            </li>
            <li>
                <div class="line">information2</div>
                <div class="line">hyperlink2</div>
            </li>
            <li>
                <div class="line">information3</div>
                <div class="line">hyperlink3</div>
            </li>
            <li>
                <div class="line">information4</div>
                <div class="line">hyperlink4</div>
            </li>
        </ul>
        <input type="submit" id="send" value="send" class="button"/>
    </div>
    

    and the css:

    .outer
    {
        display: table;
        border: 1px solid;
        padding: 5px;
    }    
    .list
    {
        list-style: none;
        padding: 5px;
    }    
    .inner
    {
        display: table-row;
        padding: 5px;
    }    
    .line
    {
        display: table-cell;
        border: 1px solid;
        border-radius: 5px;
    }    
    .button
    {
        top:50%; 
        left:50%;
    }
    

    the output is: this

    Now i want to place the button in the center of the 'outer' div no matter what is the width.

    example: i want the button to be in center even for: this. without having to change the css each time the div size changes. Even if the 'outer' div is dynamic, the button should be in the center.

    thank you.