sammarcow
sammarcow

Reputation: 2956

css html centering div within parent div

Why won't the green button center within the red parent div?

CSS

.button_green {
    background-image: url('../Images/btn_bg.jpg');
    width: 202px;
    height: 30px;
    text-align: center;
    text-transform: capitalize;
    color: white;
    text-shadow: 2px 2px #000;
    font-family: Arial;
    vertical-align: text-bottom;
    display: inline-block;
    margin: 0 auto;
   }

#col2_rightbuttons span { 
    display:inline-block;
    vertical-align:middle;
    margin:5 auto 0 auto;
}

HTML:

<div id="col2_rightbuttons" style="background-color:red;">
   <div class="button_green">
        <span>test2</span>
    </div>
</div>

enter image description here

Upvotes: 0

Views: 75

Answers (4)

neaumusic
neaumusic

Reputation: 10484

Using CSS3 (popular animation platform http://famo.us uses CSS3)

#div {
   position: absolute
   left: 50%
   top: 50%
   transform: translate(-50%, -50%)
}

translate uses the child's own sizing

Remember to add prefixes -webkit, -moz, -o, etc. and remember that any other transform property will overwrite existing transform property

Use JS to query select / concatenate an inline-css string, or you can just use a seperate container "shell" for other positional changes

Upvotes: 1

SierraOscar
SierraOscar

Reputation: 17647

The shorthand declaration of margin takes 4 arguments moving from the top and going around clockwise. Use

margin: 0 auto 0 auto;

this is the same as

margin-top: 0;
margin-right: auto;
margin-bottom: 0;
margin-left: auto;

which should centre your green button.

Upvotes: 2

michaelpri
michaelpri

Reputation: 3651

You might want to try margin-left: auto and margin-right: auto and I'm not sure if you need the display: inline-block for the parent div it can just be display: block.

Upvotes: 0

Bobby Jack
Bobby Jack

Reputation: 16048

Try display: block instead of inline-block. Plus, no need for span inside div - just combine the two and use a single element, preferably the more semantically correct button.

Upvotes: 2

Related Questions