簡體   English   中英

如何水平居中固定的定位元素

[英]How to horizontally center a fixed positioned element

我有一個圖像里面的圖層:

<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; 如果你願意,它將不起作用,將一個元素嵌套在fixed定位元素內,而不是使用margin: auto; 為了那個原因。

演示

演示2 (增加了body元素的height ,以便您可以滾動測試)

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

有些人會建議你使用display: inline-block; 對於父元素設置為text-align: center;的子元素text-align: center; ,如果這足以滿足你的需求,那么你也可以這樣做......

.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; 對於子元素,否則它將繼承父元素的text-align

請嘗試以下方法。

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

小提琴

使用transform: translate(-50%, 0);
示例代碼: 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);
}

這種方式不是跨瀏覽器,你必須設置圖層的百分比寬度,例如width:30%left:35%設置left:35%right:35%position:fixed
這是更好的,適用於所有瀏覽器RTL和LTR

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM