Html 如何水平居中定位固定的图元
我有一个里面有图像的图层:Html 如何水平居中定位固定的图元,html,css,css-position,Html,Css,Css Position,我有一个里面有图像的图层: <div id="foo"><img src="url" /></div> 但我也希望层在页面中水平居中。所以我试过: 及 但是不起作用。知道如何实现它吗?当您将一个元素定位到fixed时,它会脱离文档流,甚至margin:auto不起作用,如果需要,在固定的定位元素中嵌套一个元素,然后使用边距:auto (将高度添加到主体元素,以便您可以滚动到测试) HTML <div class="fixed"> &
<div id="foo"><img src="url" /></div>
但我也希望层在页面中水平居中。所以我试过:
及
但是不起作用。知道如何实现它吗?当您将一个元素定位到
fixed
时,它会脱离文档流,甚至margin:auto
不起作用,如果需要,在固定的定位元素中嵌套一个元素,然后使用边距:auto代码>
(将高度
添加到主体
元素,以便您可以滚动到测试)
HTML
<div class="fixed">
<div class="center"></div>
</div>
有些人会建议您使用display:inline块父元素设置为文本对齐:居中的子元素的code>代码>,如果这能满足您的需要,那么您也可以这样做
.fixed {
position: fixed;
width: 100%;
height: 40px;
background: tomato;
text-align: center;
}
.center {
display: inline-block;
width: 300px;
height: 40px;
background: blue;
}
只需确保使用text align:left代码>对于子元素,否则它将继承父元素的文本对齐方式。这种方式不跨浏览器,您必须为层设置宽度百分比,例如宽度:30%
,并设置左:35%
和右:35%
和位置:固定
这样更好,可以在所有浏览器RTL和LTR上使用,请尝试以下操作
#foo {
position: fixed;
left: 50%;
width: 30%;
transform: translate(-50%, 0);
}
使用转换:translate(-50%,0)代码>
示例代码:
CSS
尝试使用边距:0自动代码>左:50%;左边距:-大小的一半
@Zzyrk您无法应用边距:自动代码>到固定元素。谢谢。不错的选择,但是更好@Mr.Alien one。不客气,不管怎样,它们是两种完全不同的解决方案,既有优点也有缺点。
<div class="fixed">
<div class="center"></div>
</div>
.fixed {
position: fixed;
width: 100%;
height: 40px;
background: tomato;
}
.center {
width: 300px;
margin: auto;
height: 40px;
background: blue;
}
.fixed {
position: fixed;
width: 100%;
height: 40px;
background: tomato;
text-align: center;
}
.center {
display: inline-block;
width: 300px;
height: 40px;
background: blue;
}
#foo {
position: fixed;
left: 50%;
width: 30%;
transform: translate(-50%, 0);
}
div {
position: fixed;
border: 3px #555 solid;
left: 50%;
-webkit-transform: translate(-50%, 0);
-moz-transform: translate(-50%, 0);
-ms-transform: translate(-50%, 0);
transform: translate(-50%, 0);
}