css3: translateX to center element horizontally

前端 未结 4 1984
闹比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:55

    I use this technique to horizontally align some elements in situations where "text-align:center;" does not work correctly.

     position:relative; 
     left:50%;
     transform:translateX(-??em) /*or -??px or other unit of measure */
    

    ... "??" has to be tweaked depending on how wide the element is. I know it's kinda hacky, but seems to work on the screens I've tried it on so far.

    In your fiddle, applying this technique, I get:

    #parent {
        width: 300px
        height: 100px;
        background-color: black;
        border: 1px solid grey;
    }
    #child {
        position:relative;
        height: 100px;
        width: 20px;
        left:50%;
        transform: translateX(-10px); /*or  transform: translateX(-50%);*/
        -webkit-transform: translateX(-10px);/*or  -webkit-transform: translateX(-50%); */
        -ms-transform: translateX(-10px);/*or -ms-transform: translateX(-50%);*/
        background-color:red;
    }
    

    which exactly centers the child div horizontally.

提交回复
热议问题