Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/288.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Html 如何水平居中定位固定的图元_Html_Css_Css Position - Fatal编程技术网

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