Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
708 views
in Technique[技术] by (71.8m points)

html - 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;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...