css垂直居中固定定位div

时间:2022-11-10 15:34:29

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.

有任何想法吗?谢谢。

7 个解决方案

#1


16  

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

#2


78  

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

我看到的最佳解决方案是垂直和水平定位一个位置:固定div是:

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

Fiddle and source. You don't need to know the dimensions of the div and 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的尺寸,也不需要任何容器div。居中div的宽度甚至可以是一个百分比(这是我找到这个解决方案时所寻找的)。

#3


4  

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 */
}

#4


3  

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 / 2 from 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>

#5


1  

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

以下是我正在使用的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%);
}

#6


0  

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/

#7


-2  

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

问候

#1


16  

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

#2


78  

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

我看到的最佳解决方案是垂直和水平定位一个位置:固定div是:

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

Fiddle and source. You don't need to know the dimensions of the div and 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的尺寸,也不需要任何容器div。居中div的宽度甚至可以是一个百分比(这是我找到这个解决方案时所寻找的)。

#3


4  

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 */
}

#4


3  

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 / 2 from 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>

#5


1  

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

以下是我正在使用的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%);
}

#6


0  

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/

#7


-2  

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

问候