CSS如何垂直居中一个固定位置的div

55

我有一个关于一种弹出框项目的HTML代码。

<div id="lightbox">
  <img id="image" src="" />
</div>

使用以下CSS:

#lightbox{
display:none;
position:fixed;
width:100%;
text-align:center;
z-index:600;
cursor:pointer;
left:0;
top:100px;
}

#image{
position:relative;
height:600px;
border:1px solid grey;
}
为了让图像始终处于水平中心,我只需在包装器div上使用text-align:center,因此我可以100%确定它是正确的。
我遇到了垂直居中的问题,我正在使用在#lightbox属性中简单设置顶部值的解决方法。
正如您所看到的,图片的高度是已知的,因此在jQuery中很容易实现,但我正在寻找纯CSS解决方案。
有什么想法吗?谢谢。

所以我百分之百确定它会是正确的。如果你的图像是"display:block"会怎样呢? - Milche Patern
它不是。它要么是内联的,要么就没有。 - john smith
8个回答

159
我见过的既可在垂直方向又可在水平方向居中定位一个 position: fixeddiv 的最佳解决方案是:
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);

此处有代码片段来源文章。你不需要知道 div 的尺寸,并且不需要任何容器 div。即使居中的 div 的宽度是百分比(我在找到这个解决方案时就是想要这样实现的)。


1
如果您不打算支持IE8,这是一个非常棒的解决方案。 - Jose Gómez
15
如果您要居中的元素包含文本,则使用 translate 会激活 3D 硬件加速,从而导致文本变得模糊。请注意。 - Gyro
1
@Gyro 这个模糊效果有没有修复的方法? - Vivekraj K R
我只知道在webkit中的解决方案,使用css属性-webkit-font-smoothing。 - Gyro
1
position: absoluteChrome 中使文本 不模糊 - ivan.a.bovin

22

或者,您可以尝试这个方法(仅适用于您已知道图像的高度):

#image{
position:relative;
height:600px;
top: 50%;
margin-top: -300px; /* minus half the height */
border:1px solid grey;
}

1
当你已知高度时,最简单的解决方案! - john smith
10
使用'transform: translateY(-50%);',并删除'margin-top: -300px',以使其适用于任何高度。 - Sammy

7

这里有几个我正在使用的SASS mixins...希望能对某些人有所帮助:

// vertically centers as relative
@mixin vertical-align {
    position: relative;
    top: 50%;
    -webkit-transform: translateY(-50%);
    -ms-transform: translateY(-50%);
    transform: translateY(-50%);
}


// vertically centers the element as absolute
@mixin vertical-center {
    position: absolute;
    top: 50%;
    -webkit-transform: translateY(-50%);
    -ms-transform: translateY(-50%);
    transform: translateY(-50%);
}


// horizontally centers the element as absolute
@mixin horizontal-center {
    position: absolute;
    left: 50%;
    -webkit-transform: translateY(-50%);
    -ms-transform: translateY(-50%);
    transform: translateY(-50%);
}


// absolutely centers the element inside of its first non-static parent
@mixin absolute-center {
    position: absolute;
    top: 50%;
    left: 50%;
    -webkit-transform: translateY(-50%);
    -ms-transform: translateY(-50%);
    transform: translateY(-50%);
}

这应该是正确的答案,因为它不依赖于元素的高度。通过使用 transform: translateY(-50%),这将在任何高度下都能正常工作。 - Sammy
好奇,为什么已经指定了 top: 50% ,还需要使用 translateY(-50%) - dman

6

使用CSS3的视口单位和calc()函数相结合来居中轻箱,避免因硬件加速导致文字模糊的风险。该解决方案也支持响应式设计。将公式margin-top = -height / 2从固定单位转换为视口单位。

/* Overlay */
body::after
{
    position: fixed;
    z-index: 19000;
    top: 0;
    left: 0;

    display: block;

    width: 100%;
    height: 100%;

    content: ' ';

    opacity: .2;
    background-color: #000;
}

/* Lightbox */
.lightbox
{
    position: fixed;
    z-index: 15;
    top: 50%;
    width: 90vw;
    height: 90vh;
    margin: 0 5vw;
    margin-top: calc(-90vh / 2 );
}

JSFiddle

有关相对长度单位和calc()的更多信息:

详细示例

body {
    margin: 0;
}
/* The Overlay */
 body::after {
    position: fixed;
    z-index: 14;
    top: 0;
    left: 0;
    display: block;
    width: 100%;
    height: 100%;
    content:' ';
    opacity: .5;
    background-color: #000;
}
/* The Lightbox */
 .lightbox{
    position: fixed;
    z-index: 15;
    top: 50%;
    width: 60vw;
    height: 60vh;
    margin: 0 20vw;
    margin-top: calc(-60vh / 2);
    background:#fff;
    border: 1px solid white;
    border-radius: 5px;
    overflow:hidden;
    box-shadow: 0px 0px 20px 0px rgba(0, 0, 0, 0.8);
}

/* Bonus: responsive and centered image */
 .lightbox h1 {
     box-shadow: 0px 0px 20px 0px rgba(0, 0, 0, 0.8);
     position: relative;
     padding-left: 1em;
     font-family: sans-serif;
     color: #E2E8F2;
 }
.highlight
{
    color: #4E2622;
}
 .lightbox img {
    max-width: 120%;
    height: auto;
    position:absolute;
    top: 50%;
    left: 50%;
    -webkit-transform: translate(-50%, -50%);
    -moz-transform: translate(-50%, -50%);
    -ms-transform: translate(-50%, -50%);
    -o-transform: translate(-50%, -50%);
    transform: translate(-50%, -50%);
}
<div class="lightbox">
    <img src="https://pbs.twimg.com/media/CMSrIg_XAAAQU3a.jpg:large">
        <h1><span class="highlight">Sono</span> Neko その猫</h1>
</div>

<h1>Leave dead animals as gifts</h1>


<h3>Meowwww missing until dinner time</h3>

<p>Cat ipsum dolor sit amet, vommit food and eat it again. Find something else more interesting favor packaging over toy yet hide at bottom of staircase to trip human or intently stare at the same spot, but poop in litter box, scratch the walls attack feet ears back wide eyed. Scratch leg; meow for can opener to feed me. Where is my slave? i'm getting hungry purr for no reason or eat a plant, kill a hand eat a plant, kill a hand. Where is my slave? i'm getting hungry jump around on couch, meow constantly until given food, , so chase dog then run away yet stick butt in face, for poop on grasses for rub face on owner, under the bed. Brown cats with pink ears meow destroy the blinds why must they do that, and see owner, run in terror. Meowing non stop for food play time, yet stand in front of the computer screen get video posted to internet for chasing red dot poop in litter box, scratch the walls. Destroy couch leave dead animals as gifts why must they do that, for find something else more interesting hopped up on catnip sleep in the bathroom sink. Kitty power! pooping rainbow while flying in a toasted bread costume in space eat grass, throw it back up and spread kitty litter all over house. I like big cats and i can not lie. Under the bed brown cats with pink ears loves cheeseburgers has closed eyes but still sees you yet chase red laser dot. Claw drapes drink water out of the faucet and behind the couch refuse to leave cardboard box but hunt anything that moves. Rub face on owner favor packaging over toy yet play time. Hide when guests come over love to play with owner's hair tie. Purr for no reason make meme, make cute face eat a plant, kill a hand all of a sudden cat goes crazy, or stare at the wall, play with food and get confused by dust for hate dog love to play with owner's hair tie. Sleep on keyboard eat grass, throw it back up but hopped up on catnip make meme, make cute face. Pooping rainbow while flying in a toasted bread costume in space. Chase imaginary bugs destroy the blinds claws in your leg for hack up furballs. I am the best chase laser but i am the best yet meow all night having their mate disturbing sleeping humans and hunt by meowing loudly at 5am next to human slave food dispenser. Destroy the blinds. Eat a plant, kill a hand run in circles, and chew iPad power cord, and rub face on everything, and sit in box mark territory, so ignore the squirrels, you'll never catch them anyway. Present belly, scratch hand when stroked nap all day, and spot something, big eyes, big eyes, crouch, shake butt, prepare to pounce destroy couch, but put toy mouse in food bowl run out of litter box at full speed .</p>


这是唯一对我有效的解决方案。 - undefined

4
如果您想让图片具有流体大小,可以使用视图的高度作为参考:
#img {
   position: relative; /* or absolute or fixed depending on your needs */
   top: 50%;
   height: 80vh;
   margin-top: -40vh; /* minus half the height */
}

0

对我有用的解决方法是使用添加一个空的超级父元素,从那里开始 -> 每个子元素或子子元素都将垂直和水平居中。

如果您只需要水平/垂直居中,请按照代码注释中所写删除不必要的属性。

CSS:

.page-area{
      position: fixed;
      z-index: 5;/*not must but usually fixed elements require to be top*/
      height: 100%;
      width: 100%;
      display: flex;
      justify-content: center;/*define the horizontally centering*/
      align-items: center;/*define the vertically centering*/
    }

HTML:

 <div class = "page-area">
    <div>My centered element/s</div>
 </div>

-1
要垂直居中一个元素,你需要以下两个CSS属性:
display:table-cell;
vertical-align:middle;

例子:http://jsfiddle.net/yjv94/


将其应用于#lightbox,请参见我的示例。 - Ladineko
@Ladineko:这将适用于内联而非浮动元素。 此外,vertical-align属性影响内联级元素生成的框在行框内的垂直定位。 - Milche Patern

-2

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接