Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS % for vertical margin based on width instead of height

Tags:

html

css

margin

I wish to create a margin above my accountOrderButton so it can be centred vertically. I am trying to calculate half of the height of the parent div minus half of the child divs height.

This should center the button however the line 'margin-top: calc(50%);' in my CSS is returning the width of the parent div instead. How do I get the height?

HTML

<div id="accountOrder">
    <div id="accountOrderButton">
        Order Now!
    </div>
</div>

CSS

#accountOrder {
    width: 400px;
    float: left;
    height:100%;
    text-align: center;
}
#accountOrderButton {
    width: 100px;
    height: 20px;
    margin: 0 auto;
    margin-top: calc(50%);    <---- returns width instead of height
    padding: 20px;
    background-color: <?php echo $data['secondary_color']; ?>;
    border-radius: 10px;
}
like image 646
Enayet Hussain Avatar asked Feb 04 '26 07:02

Enayet Hussain


2 Answers

Use top instead of margin-top, without calc, also add left: 50%; and add transform: translate(-50%, -50%) to move it back by half of its own height and width. This also requires to use absolute position on the child and relative position on the parent:

#accountOrder {
    width: 400px;
    float: left;
    height:100%;
    text-align: center;
    position: relative; /* added */
}
#accountOrderButton {
    position: absolute; /* added */
    width: 100px;
    height: 20px;
    top: 50%;  /* changed */
    left: 50%; /* added */
    transform: translate(-50%, -50%); /* added */
    padding: 20px;
    background-color: <?php echo $data['secondary_color']; ?>;
    border-radius: 10px;
}
like image 85
Johannes Avatar answered Feb 05 '26 20:02

Johannes


As this is a common misunderstanding, it is probably worth turning @CBroe's comment into an answer so others find it easily.

The percentage is calculated with respect to the width of the generated box's containing block. Note that this is true for margin-top and margin-bottom as well.

http://w3.org/TR/CSS21/box.html#margin-properties

Also please note that calc(50%) is not calculating anything at all and is identical to 50%.

like image 28
connexo Avatar answered Feb 05 '26 19:02

connexo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!