Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

css3: translateX to center element horizontally

I'm trying to center horizontally an element: jsfiddle

<div id="parent">
    <div id="child">
</div>

On the child I have now the following css which doesn't center:

transform: translateX(50%);

Unfortunately the 50% is taken from the #child and not the parent. Is there a way to center this element using transforms (I know I can center it using, for example 'left')?

Here is the full listing of css

#parent {
    width: 300px
    height: 100px;
    background-color: black;
    border: 1px solid grey;
}
#child {
    height: 100px;
    width: 20px;
    -webkit-transform: translateX(50%);
    background-color:red;
}
like image 692
Jeanluca Scaljeri Avatar asked Dec 12 '13 08:12

Jeanluca Scaljeri


3 Answers

You were missing a position relative on your parent, position absolute on the child and the left and top values to help offset the child.

DEMO http://jsfiddle.net/nA355/6/

#parent {
    width: 300px;
    height: 100px;
    background-color: black;
    border: 1px solid grey;
    position: relative;
}
#child {
    position: absolute;
    height: 100px;
    width: 20px;
    left: 50%;
    top: 50%;
    -webkit-transform: translateX(-50%) translateY(-50%);
    -moz-transform: translateX(-50%) translateY(-50%);
    transform: translateX(-50%) translateY(-50%);
    background-color:red;
}
like image 178
2ne Avatar answered Nov 17 '22 03:11

2ne


You can do it by display flex and justify-content is center.

Example: http://jsfiddle.net/ugw9o3qp/1/

#parent {
    display: flex;
    justify-content: center;
    width: 300px;
    height: 100px;
    background-color: black;
    border: 1px solid grey;
}
#child {
    height: 100px;
    width: 20px;
    background-color:red;
}
like image 33
Akegvd Avatar answered Nov 17 '22 04:11

Akegvd


If you don't want to set the width of child-element

#child {
    display: flex;
    justify-content: center;
}
like image 38
user1891758 Avatar answered Nov 17 '22 05:11

user1891758