CSS css垂直居中固定定位div

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14583550/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 21:29:17  来源:igfitidea点击:

css vertically centering a fixed positioning div

css

提问by john smith

I have the following HTML for a sort-of lightbox project.

我有以下 HTML 用于某种灯箱项目。

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

that is using the following CSS:

使用以下 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;
}

To have the image always in the horizontal center, I am simply using text-align:center on the wrapper div, so I am 100% sure it will be correct.

为了使图像始终位于水平中心,我只是在包装器 div 上使用 text-align:center,所以我 100% 确定它是正确的。

I am facing problems with the vertical centering and I am using a workaround of simply setting the top value in the #lightbox properties.

我面临垂直居中的问题,我正在使用一种解决方法,只需在 #lightbox 属性中设置最高值。

As you can see the height of the image is known, so it is easily doable in jQuery but I am looking for a pure CSS solution.

正如您所看到的,图像的高度是已知的,因此在 jQuery 中很容易实现,但我正在寻找纯 CSS 解决方案。

Any ideas? Thanks.

有任何想法吗?谢谢。

采纳答案by Gareth Cornish

Alternatively, you could try this (only works if you know the height of the image):

或者,您可以尝试此操作(仅当您知道图像的高度时才有效):

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

回答by Vincent

The best solution I've seen for both vertically and horizontally centering a position: fixeddivis:

我见过的垂直和水平居中 a 的最佳解决方案position: fixeddiv是:

position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);

Fiddleand source. You don't need to know the dimensions of the divand it doesn't require any container divs. The centered div's width can even be a percentage (which was what I was looking for when I found this solution).

小提琴。您不需要知道 的尺寸,div也不需要任何 container div。居中div的宽度甚至可以是一个百分比(这是我找到这个解决方案时所寻找的)。

回答by Playnox

Here are couple SASS mixins I'm using... I hope this is going to help someone:

这是我正在使用的几个 SASS mixin……我希望这会对某人有所帮助:

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

回答by drjorgepolanco

If you want the image to have a fluid size, you can use the height of the view as a reference:

如果您希望图像具有流体尺寸,则可以使用视图的高度作为参考:

#img {
   position: relative; /* or absolute or fixed depending on your needs */
   top: 50%;
   height: 80vh;
   margin-top: -40vh; /* minus half the height */
}

回答by Bill Alexy

Use a combo of CSS3's viewport units and calc( ) to center a lightbox without the risk of blurring text due to hardware acceleration. This solution is also responsive. Convert the formula margin-top = -height / 2from fixed units to viewport units

使用 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

JSFiddle

More information on relative length units and calc( ):

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

Detailed Example

详细示例

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>

回答by Ladineko

To vertically center an item you need the following 2 css attributes :

要将项目垂直居中,您需要以下 2 个 css 属性:

display:table-cell;
vertical-align:middle;

example : http://jsfiddle.net/yjv94/

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

回答by Dedalos01

have you check this soution?:

你检查过这个吗?:

CSS: Vertically align div when no fixed size of the div is known

CSS:当不知道 div 的固定大小时垂直对齐 div

here you dont need to have a height declared.

在这里您不需要声明高度。

Regards

问候