How to horizontally center a fixed positioned element

六月ゝ 毕业季﹏ 提交于 2019-12-17 21:29:01

问题


I have a layer with an image inside:

<div id="foo"><img src="url" /></div>

and it is fixed positioned:

#foo {
    position: fixed;
}

but I also want the layer to be horizontally centered in the page. So I've tried: http://jsfiddle.net/2BG9X/

#foo {
    position: fixed;
    margin: auto
}

and http://jsfiddle.net/2BG9X/1/

#foo {
    position: fixed;
    left: auto;
}

but doesn't work. Any idea of how to achieve it?


回答1:


When you position an element to fixed, it gets out of the document flow, where even margin: auto; won't work, if you want, nest an element inside that fixed positioned element and than use margin: auto; for that.

Demo

Demo 2 (Added height to the body element so that you can scroll to test)

HTML

<div class="fixed">
    <div class="center"></div>
</div>

CSS

.fixed {
    position: fixed;
    width: 100%;
    height: 40px;
    background: tomato;
}

.center {
    width: 300px;
    margin: auto;
    height: 40px;
    background: blue;
}

Some will suggest you to use display: inline-block; for the child element with the parent set to text-align: center;, well if that suffice your needs, than you can go for that too...

.fixed {
    position: fixed;
    width: 100%;
    height: 40px;
    background: tomato;
    text-align: center;
}

.center {
    display: inline-block;
    width: 300px;
    height: 40px;
    background: blue;
}

Demo 2

Just make sure you use text-align: left; for the child element, else it will inherit the text-align of the parent element.




回答2:


Use transform: translate(-50%, 0);
Example Code: http://codepen.io/fcalderan/pen/uJkrE

CSS

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



回答3:


Try the following.

#foo {
    position: fixed;
    left: 50%;
    width: 30%;
    transform: translate(-50%, 0);
}

Fiddle




回答4:


this way not cross browser you must set percent width for layer e.g width:30% and set left:35% and right:35% and position:fixed
this is better and work on all browser RTL and LTR



来源:https://stackoverflow.com/questions/21309975/how-to-horizontally-center-a-fixed-positioned-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!