css3: translateX to center element horizontally

前端 未结 4 1981
闹比i
闹比i 2020-12-19 08:01

I\'m trying to center horizontally an element: jsfiddle

On the child I

4条回答
  •  無奈伤痛
    2020-12-19 08:37

    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;
    }
    

提交回复
热议问题