水平居中对齐绝对对象 [英] center align position absolute object horizontally
问题描述
我有一个元素的位置是绝对的,我面临的唯一问题是我已经应用了一些属性以使其水平居中对齐,并且在mozilla上运行良好,但是在chrome上却无法使用相同的属性 这是我的代码
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;
}
将元素居中的一个有用技巧是将transform: translate
样式与top
,margin-left
left
或margin-top
一起使用./p>
要回答您的问题,必须将以下样式应用于.slider a.downarrow
元素:
left: 50%;
transform: translateX(-50%);
之所以起作用,是因为如果translate
与百分比值一起使用,则其值是根据其所应用的元素的高度/宽度来计算的.
top
,margin-left
,left
和margin-top
百分比值是根据父元素或在元素基于最近的父元素position: relative/absolute
应用于position: absolute
的情况下计算的.>
要将元素居中,只需将50%
的值应用于top
,margin-left
left
或margin-top
,将-50%
的值应用于translate
.
对于left
和margin-left
,您必须使用translateX(-50%)
,而对于其他translateY(-50%)
.
编辑:添加了说明
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;
}
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
这篇关于水平居中对齐绝对对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!