Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

css - center align position absolute object horizontally

i have an element whose position is absolute the only issue i am facing is i have applied some properties to align it center horizontally and it is working fine on mozilla but the same properties are not working on chrome here's my code

html

<a href="#section1" class="scrollTo downarrow"><img src="images/navbar_downarrow.png" class="img-responsive"/></a>

css

    .slider{
        position: relative;
        background-image: url("../images/slider.jpg");
        background-size: 100% 100%;
        background-repeat: no-repeat;
    }
    .slider a.downarrow{
        position: absolute;
        margin-left: auto;
        margin-right: auto;
        left: 0;
        right: 0;
        bottom: 20px;
        display: table;
    }
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

A useful trick to center elements is to use the transform: translate style together with either top, margin-left left or margin-top.

To answer your question, you have to apply the following styles to your .slider a.downarrow element:

left: 50%;
transform: translateX(-50%);

The way this works is because if translate is used with a percentage value, its value is calculated based on the elements height/width on which it is applied on.

top, margin-left left and margin-top percentage values are calculated based on the parent element or in case the element has position: absolute applied to it based on the nearest parent with position: relative/absolute.

To center an element you just need to apply a value of 50% to either top, margin-left left or margin-top and a value of -50% to translate.

For left and margin-left you have to use translateX(-50%) and for the others translateY(-50%).

EDIT: Added an explanation


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.8k users

...