如何水平居中固定定位的元素 [英] How to horizontally center a fixed positioned element

查看:144
本文介绍了如何水平居中固定定位的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个图层里面的图层:

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

且位置固定:

  #foo {
position:fixed;
}

但我还希望图层在页面中水平居中。所以我试过:
http://jsfiddle.net/2BG9X/

  #foo {
position:fixed;
margin:auto
}


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

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

但不工作。

解决方案

将元素放置到 fixed ,它离开文档流程,其中甚至 margin:auto; 将无法工作,如果你想,嵌套一个元素在固定定位元素,而不是使用 margin:auto;



a href =http://jsfiddle.net/5cJ49/> 演示



Demo 2 height 添加到<$ c $

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






对父元素设置为 text-align:center; 的子元素使用 display:inline-block;

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

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

演示2



请务必使用 text-align:left; code>为子元素,否则它将继承父元素的 text-align


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?

解决方案

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.

这篇关于如何水平居中固定定位的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆