繁体   English   中英

如何使用 CSS 为所有浏览器垂直居中 div 元素?

[英]How can I vertically center a div element for all browsers using CSS?

我想用 CSS 将一个div垂直居中。 我不需要表格或 JavaScript,只需要纯 CSS。 我找到了一些解决方案,但它们都缺少对 Internet Explorer 6 的支持。

<body>
    <div>Div to be aligned vertically</div>
</body>

如何在所有主流浏览器(包括 Internet Explorer 6)中将div垂直居中?

下面是我可以构建的最好的全方位解决方案,用于垂直和水平居中固定宽度、灵活高度的内容框。 它已经过测试并适用于最新版本的 Firefox、Opera、Chrome 和 Safari。

 .outer { display: table; position: absolute; top: 0; left: 0; height: 100%; width: 100%; } .middle { display: table-cell; vertical-align: middle; } .inner { margin-left: auto; margin-right: auto; width: 400px; /* Whatever width you want */ }
 <div class="outer"> <div class="middle"> <div class="inner"> <h1>The Content</h1> <p>Once upon a midnight dreary...</p> </div> </div> </div>

查看具有动态内容的工作示例

我内置了一些动态内容来测试灵活性,并且很想知道是否有人发现它有任何问题。 它也应该适用于居中的叠加层——灯箱、弹出窗口等。

最简单的方法是以下三行CSS:

1)位置:相对;

2) 最高:50%;

3) 变换:translateY(-50%);

以下是一个例子

 div.outer-div { height: 170px; width: 300px; background-color: lightgray; } div.middle-div { position: relative; top: 50%; -webkit-transform: translateY(-50%); -ms-transform: translateY(-50%); transform: translateY(-50%); }
 <div class='outer-div'> <div class='middle-div'> Test text </div> </div>

还有一个我在列表中看不到的:

.Center-Container {
  position: relative;
  height: 100%;
}

.Absolute-Center {
  width: 50%;
  height: 50%;
  overflow: auto;
  margin: auto;
  position: absolute;
  top: 0; left: 0; bottom: 0; right: 0;
  border: solid black;
}
  • 跨浏览器(包括 Internet Explorer 8 - 没有 hack 的 Internet Explorer 10!)
  • 响应百分比和最小值/最大值
  • 居中而不考虑填充(没有盒子大小!)
  • 必须声明height (请参阅可变高度
  • 推荐设置overflow: auto防止内容溢出(见溢出)

来源: CSS 中的绝对水平和垂直居中

现在Flexbox解决方案对于现代浏览器来说是一种非常简单的方法,所以我向您推荐这个:

 .container { display: flex; align-items: center; justify-content: center; height: 100%; background: green; } body, html { height: 100%; }
 <div class="container"> <div>Div to be aligned vertically</div> </div>

实际上,您需要两个 div 用于垂直居中。 包含内容的 div 必须具有宽度和高度。

 #container { position: absolute; top: 50%; margin-top: -200px; /* Half of #content height */ left: 0; width: 100%; } #content { width: 624px; margin-left: auto; margin-right: auto; height: 395px; border: 1px solid #000000; }
 <div id="container"> <div id="content"> <h1>Centered div</h1> </div> </div>

这是结果

2020 年编辑:仅当您需要支持Internet Explorer 8等旧浏览器时才使用此功能(您应该拒绝这样做😉)。 如果没有,请使用Flexbox


这是我找到的最简单的方法,我一直在使用它(此处为 jsFiddle 演示)。

感谢 CSS Tricks 的 Chris Coyier撰写本文

 html, body{ height: 100%; margin: 0; } .v-wrap{ height: 100%; white-space: nowrap; text-align: center; } .v-wrap:before{ content: ""; display: inline-block; vertical-align: middle; width: 0; /* adjust for white space between pseudo element and next sibling */ margin-right: -.25em; /* stretch line height */ height: 100%; } .v-box{ display: inline-block; vertical-align: middle; white-space: normal; }
 <div class="v-wrap"> <article class="v-box"> <p>This is how I've been doing it for some time</p> </article> </div>

支持从 Internet Explorer 8 开始。

经过大量研究,我终于找到了最终的解决方案。 它甚至适用于浮动元素。 查看源代码

.element {
    position: relative;
    top: 50%;
    transform: translateY(-50%); /* or try 50% */
}

使用CSS Flexbox align-items属性来实现这一点。

 html, body { height: 100%; } body { display: flex; align-items: center; }
 <div>This is centered vertically</div>

要将 div 在页面上居中,请检查 fiddle link

 #vh { margin: auto; position: absolute; top: 0; left: 0; bottom: 0; right: 0; } .box{ border-radius: 15px; box-shadow: 0 0 8px rgba(0, 0, 0, 0.4); padding: 25px; width: 100px; height: 100px; background: white; }
 <div id="vh" class="box">Div to be aligned vertically</div>

另一种选择是使用弹性框,检查小提琴链接

 .vh { background-color: #ddd; height: 400px; align-items: center; display: flex; } .vh > div { width: 100%; text-align: center; vertical-align: middle; }
 <div class="vh"> <div>Div to be aligned vertically</div> </div>

另一种选择是使用 CSS 3 转换:

 #vh { position: absolute; top: 50%; left: 50%; /*transform: translateX(-50%) translateY(-50%);*/ transform: translate(-50%, -50%); } .box{ border-radius: 15px; box-shadow: 0 0 8px rgba(0, 0, 0, 0.4); padding: 25px; width: 100px; height: 100px; background: white; }
 <div id="vh" class="box">Div to be aligned vertically</div>

最简单的解决方案如下:

 .outer-div{ width: 100%; height: 200px; display: flex; border:1px solid #000; } .inner-div{ margin: auto; text-align: center; border: 1px solid red; }
 <div class="outer-div"> <div class="inner-div"> Hey there! </div> </div>

不幸的是——但并不奇怪——解决方案比人们希望的要复杂。 同样不幸的是,您需要在要垂直居中的 div 周围使用其他 div。

对于 Mozilla、Opera、Safari 等符合标准的浏览器,您需要将外部 div 设置为显示为表格,将内部 div 设置为显示为表格单元格——然后可以垂直居中。 对于 Internet Explorer,您需要将内部 div绝对定位在外部 div 内,然后将顶部指定为50% 以下页面很好地解释了这种技术并提供了一些代码示例:

还有一种使用 JavaScript 进行垂直居中的技术。 内容与 JavaScript 和 CSS 的垂直对齐证明了这一点。

如果有人只关心 Internet Explorer 10(及更高版本),请使用Flexbox

 .parent { width: 500px; height: 500px; background: yellow; display: -webkit-flex; display: -ms-flexbox; display: flex; -webkit-justify-content: center; -ms-flex-pack: center; justify-content: center; -webkit-align-items: center; -ms-flex-align: center; align-items: center; } .centered { width: 100px; height: 100px; background: blue; }
 <div class="parent"> <div class="centered"></div> </div>

Flexbox 支持: http ://caniuse.com/flexbox

将元素垂直居中的现代方法是使用flexbox

你需要一个父母来决定身高和一个孩子来居中。

下面的示例将 div 居中到浏览器的中心。 重要的是(在我的示例中)将height: 100%设置为bodyhtml ,然后将min-height: 100%设置为您的容器。

 body, html { background: #F5F5F5; box-sizing: border-box; height: 100%; margin: 0; } #center_container { align-items: center; display: flex; min-height: 100%; } #center { background: white; margin: 0 auto; padding: 10px; text-align: center; width: 200px; }
 <div id='center_container'> <div id='center'>I am center.</div> </div>

使用 CSS 的 flex 属性。

解决方案#1

 .parent { width: 400px; height:200px; background: blue; display: flex; align-items: center; justify-content:center; } .child { width: 75px; height: 75px; background: yellow; }
 <div class="parent"> <div class="child"></div> </div>

使用display: flex; margin: auto;

解决方案#2

 .parent { width: 400px; height:200px; background: blue; display: flex; } .child { width: 75px; height: 75px; background: yellow; margin:auto; }
 <div class="parent"> <div class="child"></div> </div>

显示文本中心

解决方案#3

 .parent { width: 400px; height: 200px; background: yellow; display: flex; align-items: center; justify-content:center; }
 <div class="parent">Center</div>

使用百分比(%)高度和宽度。

解决方案#4

 .parent { position: absolute; height:100%; width:100%; background: blue; display: flex; align-items: center; justify-content:center; } .child { width: 75px; height: 75px; background: yellow; }
 <div class="parent"> <div class="child"></div> </div>

仅垂直居中

如果您不关心 Internet Explorer 6 和 7,则可以使用涉及两个容器的技术。

外容器:

  • 应该有display: table;

内部容器:

  • 应该有display: table-cell;
  • 应该有vertical-align: middle;

内容框:

  • 应该有display: inline-block;

您可以将任何您想要的内容添加到内容框中,而无需关心它的宽度或高度!

演示:

 body { margin: 0; } .outer-container { position: absolute; display: table; width: 100%; /* This could be ANY width */ height: 100%; /* This could be ANY height */ background: #ccc; } .inner-container { display: table-cell; vertical-align: middle; } .centered-content { display: inline-block; background: #fff; padding: 20px; border: 1px solid #000; }
 <div class="outer-container"> <div class="inner-container"> <div class="centered-content"> Malcolm in the Middle </div> </div> </div>

另见这个小提琴


水平和垂直居中

如果要水平和垂直居中,还需要以下内容。

内部容器:

  • 应该有text-align: center;

内容框:

  • 应该将水平文本对齐重新调整为例如text-align: left; text-align: right; , 除非您希望文本居中

演示:

 body { margin: 0; } .outer-container { position: absolute; display: table; width: 100%; /* This could be ANY width */ height: 100%; /* This could be ANY height */ background: #ccc; } .inner-container { display: table-cell; vertical-align: middle; text-align: center; } .centered-content { display: inline-block; text-align: left; background: #fff; padding: 20px; border: 1px solid #000; }
 <div class="outer-container"> <div class="inner-container"> <div class="centered-content"> Malcolm in the Middle </div> </div> </div>

另见这个小提琴

 .center { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); /* (x, y) => position */ -ms-transform: translate(-50%, -50%); /* IE 9 */ -webkit-transform: translate(-50%, -50%); /* Chrome, Safari, Opera */ } .vertical { position: absolute; top: 50%; //left: 0; transform: translate(0, -50%); /* (x, y) => position */ } .horizontal { position: absolute; //top: 0; left: 50%; transform: translate(-50%, 0); /* (x, y) => position */ } div { padding: 1em; background-color: grey; color: white; }
 <body> <div class="vertical">Vertically left</div> <div class="horizontal">Horizontal top</div> <div class="center">Vertically Horizontal</div> </body>

相关: 将图像居中

当我不得不回到这个问题时,这总是我要去的地方。

对于那些不想跳的人:

  1. 将父容器指定为position:relativeposition:absolute
  2. 在子容器上指定一个固定高度。
  3. 在子容器上设置position:absolutetop:50%以将顶部向下移动到父容器的中间。
  4. 设置 margin-top:-yy ,其中 yy 是子容器高度的一半以向上偏移项目。

代码中的一个示例:

<style type="text/css">
    #myoutercontainer {position:relative}
    #myinnercontainer {position:absolute; top:50%; height:10em; margin-top:-5em}
</style>
...
<div id="myoutercontainer">
    <div id="myinnercontainer">
        <p>Hey look! I'm vertically centered!</p>
        <p>How sweet is this?!</p>
    </div>
</div>

它可以通过两种方式完成

body{
left: 50%; 
top:50%; 
transform: translate(-50%, -50%); 
height: 100%; 
width: 100%; 
}

或者

使用弹性

body {
    height:100%
    width:100%
    display: flex;
    justify-content: center;
    align-items: center;
}

align-items:center; 使内容垂直居中

justify-content: center; 使内容水平居中

我刚刚写了这个 CSS,要了解更多信息,请阅读: 这篇文章用 3 行 CSS 垂直对齐任何东西

.element {
    position: relative;
    top: 50%;
    transform: perspective(1px) translateY(-50%);
}

对于新手,请尝试:

display: flex;
align-items: center;
justify-content: center;

使用transform的三行代码实际上适用于现代浏览器和 Internet Explorer:

.element{
     position: relative;
     top: 50%;
     transform: translateY(-50%);
     -moz-transform: translateY(-50%);
     -webkit-transform: translateY(-50%);
     -ms-transform: translateY(-50%);
}

我添加了这个答案,因为我在这个答案的先前版本中发现了一些不完整(并且 Stack Overflow 不允许我简单地发表评论)。

  1. 如果当前 div 在 body 中并且没有容器 div,则 'position' relative 会破坏样式。 然而“固定”似乎有效,但它显然修复了视口中心的内容位置:相对

  2. 此外,我使用这种样式来使一些覆盖 div 居中,并发现在 Mozilla 中,这个转换后的 div 内的所有元素都失去了它们的底部边框。 可能是渲染问题。 但是仅向其中一些添加最小的填充就可以正确呈现它。 Chrome 和 Internet Explorer(出人意料地)无需任何填充即可渲染这些框没有内部填充的 Mozilla带有填充物的 Mozilla

CSS 网格

 body, html { margin: 0; } body { display: grid; min-height: 100vh; align-items: center; }
 <div>Div to be aligned vertically</div>

Billbad 的答案仅适用于.inner div 的固定宽度。 此解决方案通过将属性text-align: center添加到.outer div 来实现动态宽度。

 .outer { position: absolute; display: table; width: 100%; height: 100%; text-align: center; } .middle { display: table-cell; vertical-align: middle; } .inner { text-align: center; display: inline-block; width: auto; }
 <div class="outer"> <div class="middle"> <div class="inner"> Content </div> </div> </div>

就这样做:在你的div添加类:

.modal {
  margin: auto;
  position: absolute;
  top: 0;
  right: 0;
  left: 0;
  bottom: 0;
  height: 240px;
}

并阅读这篇文章以获得解释。 注意: Height是必需的。

.center{
    display: grid;
    place-items: center;
}

我是这样做的(相应地更改宽度、高度、上边距和左边距):

.wrapper {
    width: 960px;
    height: 590px;
    position: absolute;
    top: 50%;
    left: 50%;
    margin-top: -295px;
    margin-left: -480px;
}
<div class="wrapper"> -- Content -- </div>

我想用CSS将div垂直居中。 我不需要表或JavaScript,而只需要纯CSS。 我找到了一些解决方案,但是所有这些解决方案都缺少Internet Explorer 6支持。

<body>
    <div>Div to be aligned vertically</div>
</body>

如何在所有主要浏览器(包括Internet Explorer 6)中垂直居中放置div

不回答浏览器兼容性问题,但也提到新的 Grid 和不太新的 Flexbox 功能。

网格

来自: Mozilla - 网格文档 - 垂直对齐 Div

浏览器支持:网格浏览器支持

CSS:

.wrapper {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  grid-gap: 10px;
  grid-auto-rows: 200px;
  grid-template-areas: 
    ". a a ."
    ". a a .";
}
.item1 {
  grid-area: a;
  align-self: center;
  justify-self: center;
}

HTML:

<div class="wrapper">
 <div class="item1">Item 1</div>
</div>

弹性盒

浏览器支持: Flexbox 浏览器支持

CSS:

display: -webkit-box;
display: -moz-box;
display: -ms-flexbox;
display: -webkit-flex;
display: flex;
align-items: center;
justify-content: center;

我认为不使用 Flexbox 的所有浏览器的可靠解决方案 - “align-items: center;” 是 display: table 和 vertical-align: middle; 的组合。

CSS

.vertically-center
{
    display: table;

    width: 100%;  /* Optional */
    height: 100%; /* Optional */
}

.vertically-center > div
{
    display: table-cell;
    vertical-align: middle;
}

HTML

<div class="vertically-center">
    <div>
        <div style="border: 1px solid black;">some text</div>
    </div>
</div>

‣演示: https ://jsfiddle.net/6m640rpp/

特别是对于具有相对(未知)高度的父 div,未知解决方案中的居中对我来说非常有用。 文章中有一些非常好的代码示例。

它在 Chrome、Firefox、Opera 和 Internet Explorer 中进行了测试。

 /* This parent can be any width and height */ .block { text-align: center; } /* The ghost, nudged to maintain perfect centering */ .block:before { content: ''; display: inline-block; height: 100%; vertical-align: middle; margin-right: -0.25em; /* Adjusts for spacing */ } /* The element to be centered, can also be of any width and height */ .centered { display: inline-block; vertical-align: middle; width: 300px; }
 <div style="width: 400px; height: 200px;"> <div class="block" style="height: 90%; width: 100%"> <div class="centered"> <h1>Some text</h1> <p>Any other text..."</p> </div> </div> </div>

使用 Flexbox 可以轻松地将内容居中。 以下代码显示了内容需要居中的容器的 CSS:

.absolute-center {
    display: -ms-flexbox;
    display: -webkit-flex;
    display: flex;

    -ms-flex-align: center;
    -webkit-align-items: center;
    -webkit-box-align: center;

    align-items: center;
}

我最近发现了一个技巧:你需要使用top 50% ,然后你做一个translateY(-50%)

 .outer-div { position: relative; height: 150px; width: 150px; background-color: red; } .centered-div { position: absolute; top: 50%; -webkit-transform: translateY(-50%); -ms-transform: translateY(-50%); transform: translateY(-50%); background-color: white; }
 <div class='outer-div'> <div class='centered-div'> Test text </div> </div>

我发现这是最有用的..它提供了最准确的“ H”布局,并且非常易于理解。

此标记的好处是,您可以在一个位置->“ PageContent”中定义内容大小。
页面背景的颜色及其水平边距在其相应的div中定义。

<div id="PageLayoutConfiguration" 
     style="display: table;
     position:absolute; top: 0px; right: 0px; bottom: 0px; left: 0px;
     width: 100%; height: 100%;">

        <div id="PageBackground" 
             style="display: table-cell; vertical-align: middle;
             background-color: purple;">

            <div id="PageHorizontalMargins"
                 style="width: 100%;
                 background-color: seashell;">

                <div id="PageContent" 
                     style="width: 1200px; height: 620px; margin: 0 auto;
                     background-color: grey;">

                     my content goes here...

                </div>
            </div>
        </div>
    </div>

在这里,CSS分开了:

<div id="PageLayoutConfiguration">
     <div id="PageBackground">
          <div id="PageHorizontalMargins">
               <div id="PageContent">
                     my content goes here...
               </div>
          </div>
     </div>
</div>

#PageLayoutConfiguration{
   display: table; width: 100%; height: 100%;
   position:absolute; top: 0px; right: 0px; bottom: 0px; left: 0px;
}

#PageBackground{
   display: table-cell; vertical-align: middle;
   background-color: purple;
}

#PageHorizontalMargins{
   style="width: 100%;
   background-color: seashell;
}
#PageContent{
   width: 1200px; height: 620px; margin: 0 auto;
   background-color: grey;
}

我用这个。 它适用于 Internet Explorer 8 及更高版本:

height:268px - 对于display:table就像 min-height 一样。

CSS:

* {
  padding: 0;
  margin: 0;
}
body {
  background: #cc9999;
}
p {
  background: #f0ad4e;
}
#all {
  margin: 200px auto;
}
.ff-valign-wrap {
  display: table;
  width: 100%;
  height: 268px;
  background: #ff00ff;
}
.ff-valign {
  display: table-cell;
  height: 100%;
  vertical-align: middle;
  text-align: center;
  background: #ffff00;
}

HTML:

<body>

  <div id="all">
    <div class="ff-valign-wrap">
      <div class="ff-valign">
        <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Amet, animi autem doloribus earum expedita, ipsum laboriosam nostrum nulla officiis optio quam quis quod sunt tempora tenetur veritatis vero voluptatem voluptates?</p>
        <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Amet, animi autem doloribus earum expedita, ipsum laboriosam nostrum nulla officiis optio quam quis quod sunt tempora tenetur veritatis vero voluptatem voluptates?</p>
        <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Amet, animi autem doloribus earum expedita, ipsum laboriosam nostrum nulla officiis optio quam quis quod sunt tempora tenetur veritatis vero voluptatem voluptates?</p>
        <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Amet, animi autem doloribus earum expedita, ipsum laboriosam nostrum nulla officiis optio quam quis quod sunt tempora tenetur veritatis vero voluptatem voluptates?</p>
        <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Amet, animi autem doloribus earum expedita, ipsum laboriosam nostrum nulla officiis optio quam quis quod sunt tempora tenetur veritatis vero voluptatem voluptates?</p>
        <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Amet, animi autem doloribus earum expedita, ipsum laboriosam nostrum nulla officiis optio quam quis quod sunt tempora tenetur veritatis vero voluptatem voluptates?</p>
        <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Amet, animi autem doloribus earum expedita, ipsum laboriosam nostrum nulla officiis optio quam quis quod sunt tempora tenetur veritatis vero voluptatem voluptates?</p>
      </div>
    </div>
  </div>

</body>

以下内容适用于我的情况,并在 Firefox 中进行了测试。

#element {
    display: block;
    transform: translateY(50%);
    -moz-transform: translateY(50%);
    -webkit-transform: translateY(50%);
    -ms-transform: translateY(50%);
}

div 的高度和父级的高度是动态的。 当同一个父元素上有其他元素高于目标元素时,我会使用它,其中两个元素都水平内联放置。

这个解决方案对我来说适用于块元素(例如,<div>)。 我使用颜色使解决方案更清晰。

HTML:

<main class="skin_orange">
    <p>As you can the the element/box is vertically centered</p>
    <div class="bigBox skin_blue">Blue Box</div>
</main>

CSS:

main {
    position: relative;
    width: 400px;
    height: 400px;
}

.skin_orange {
    outline: thin dotted red;
    background: orange;
}

.bigBox {
    width: 150px;
    height: 150px;
    position: absolute;
    top: 50%;
    transform: translateY(-50%);
}

.skin_blue {
    background-color: blue;
}

JSFiddle 代码演示

我刚刚找到了另一种对我有用的方法:

<div class="container">
  <div class="vertical">
     <h1>Welcome</h1>
     <h2>Aligned Vertically</h2>
     <a href="#">Click ME</a>
   </div>
</div>

CSS

.vertical{
  top: 50%;
  -webkit-transform: translateY(-50%);
  -ms-transform: translateY(-50%);
  transform: translateY(-50%);
}

更多信息

垂直和水平中心

HTML

<div id="dialog">Centered Dialog</div>

CSS

#dialog {
    position:fixed; top:50%; left:50%; z-index:99991;
    width:300px; height:60px;
    margin-top:-150px;  /* half of the width */
    margin-left:-30px; /* half of the height */}

享受!

通过使用transform属性,我们可以轻松地做一个垂直居中的 div。

 .main-div { background: none repeat scroll 0 0 #999; font-size: 18px; height: 450px; max-width: 850px; padding: 15px; } .vertical-center { background: none repeat scroll 0 0 #1FA67A; color: #FFFFFF; padding: 15px; position: relative; top: 50%; transform: translateY(-50%); -moz-transform: translateY(-50%); -webkit-transform: translateY(-50%); -ms-transform: translateY(-50%); -o-transform: translateY(-50%); }
 <div class="main-div"> <div class="vertical-center"> <span>"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."</span> </div> </div>

完整文章请看这里

最好的做法是:

#vertalign{
  height: 300px;
  width: 300px;
  position: absolute;
  top: calc(50vh - 150px); 
}

150 像素,因为在这种情况下这是 div 高度的一半。

声明这个 Mixin:

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

然后将其包含在您的元素中:

.element{
    @include vertical-align();
}

这是迄今为止最简单的方法,也适用于非阻塞元素。 唯一的缺点是它是 Flexbox,因此,较旧的浏览器将不支持此功能。

<div class="sweet-overlay">
    <img class="centered" src="http://jimpunk.com/Loading/loading83.gif" />
</div>

代码笔链接:

http://codepen.io/damianocel/pen/LNOdRp

这里的重点是,为了垂直居中,我们需要定义一个父元素(容器),并且 img 的高度必须小于父元素。

此方法不使用任何变换。 所以它没有输出变得模糊的问题。

position: absolute;
width: 100vw;
top: 25%;
bottom: 25%;
text-align: center;

由于每次我需要将 div 垂直居中时,我都会一遍又一遍地搜索它,而这个答案总是最先出现的,我将把它留给未来的我(因为提供的解决方案都不适合我的需要):

因此,如果已经在使用引导程序,则可以按如下方式完成:

<div style="min-height: 100vh;" class="align-items-center row">
    <div class="col" style="margin: auto; max-width: 750px;"> //optional style to center horizontally as well

    //content goes here

    </div>
</div>

我为想要的人分享了简短版本。

 .firstDivision { display: table; position: absolute; top: 0; left: 0; height: 100%; width: 100%; } .firstDivision .verticalCenter { text-align: center; display: table-cell; vertical-align: middle; }
 <div class="firstDivision"> <div class="verticalCenter"> Text was centered for Vertical. </div> </div>

居中是CSS最困难的方面之一。

这些方法本身通常并不难理解。 相反,更多的是因为有很多方法可以让事物center

您使用的方法可能会有所不同,具体取决于您尝试居中的 HTML 元素,或者您是horizontally居中还是vertically居中。

水平居中

水平居中元素通常比垂直居中更容易。 以下是您可能希望水平居中的一些常见元素以及不同的实现方式。

使用 CSS Text-Align Center 属性居中文本

要水平居中文本或链接,只需使用值为centertext-align属性:

HTML

<div class="container">
  <p>Hello, (centered) World!</p>
</div>

CSS

.container {
  font-family: arial;
  font-size: 24px;
  margin: 25px;
  width: 350px;
  height: 200px;
  outline: dashed 1px black;
}

p {
  /* Center horizontally*/
  text-align: center;
}

使用 CSS Margin Auto 居中 Div

使用值为0 auto的简写margin属性来水平居中块级元素,例如div

HTML

<div class="container">
  <div class="child"></div>
</div>

CSS

.container {
  font-family: arial;
  font-size: 24px;
  margin: 25px;
  width: 350px;
  height: 200px;
  outline: dashed 1px black;
}

.child {
  width: 50px;
  height: 50px;
  background-color: red;
  /* Center horizontally*/
  margin: 0 auto;
}

使用 Flexbox 将 Div 水平居中

Flexbox是将内容置于页面center的最现代的方式,并且使设计响应式布局比以前更容易。 但是,某些旧版浏览器(如 Internet Explorer)并不完全支持它。

要使用 Flexbox 将元素horizontally center ,只需将display: flexjustify-content: center应用于parent element

HTML

<div class="container">
  <div class="child"></div>
</div>

CSS

.container {
  font-family: arial;
  font-size: 24px;
  margin: 25px;
  width: 350px;
  height: 200px;
  outline: dashed 1px black;
  /* Center child horizontally*/
  display: flex;
  justify-content: center;
}

.child {
  width: 50px;
  height: 50px;
  background-color: red;
}

垂直居中

如果没有像 Flexbox 这样的现代方法,将元素垂直居中可能是一件很麻烦的事情。 在这里,我们将首先回顾一些旧的垂直居中方法,然后向您展示如何使用 Flexbox 来实现。

如何使用 CSS 绝对定位和负边距使 Div 垂直居中

很长一段时间,这是垂直居中的首选方法。 对于此方法,您必须知道要居中的元素的高度。

首先,将父元素的position属性设置为relative

然后对于子元素,将position属性设置为absolute并将 top 设置为50%

HTML

<div class="container">
  <div class="child"></div>
</div>

CSS

.container {
  font-family: arial;
  font-size: 24px;
  margin: 25px;
  width: 350px;
  height: 200px;
  outline: dashed 1px black;
  /* Setup */
  position: relative;
}

.child {
  width: 50px;
  height: 50px;
  background-color: red;
  /* Center vertically */
  position: absolute;
  top: 50%;
}

但这实际上只是垂直居中子元素的顶部边缘。

要使子元素真正居中,请将margin-top属性设置为-(half the child element's height)

.container {
  font-family: arial;
  font-size: 24px;
  margin: 25px;
  width: 350px;
  height: 200px;
  outline: dashed 1px black;
  /* Setup */
  position: relative;
}

.child {
  width: 50px;
  height: 50px;
  background-color: red;
  /* Center vertically */
  position: absolute;
  top: 50%;
  margin-top: -25px; /* Half this element's height */
}

使用 Transform 和 Translate 将 Div 垂直居中

如果您不知道要居中的元素的高度(或者即使您知道),这种方法是一个绝妙的技巧。

这种方法与上面的负边距方法非常相似。 将父元素的position属性设置为relative

对于子元素,将position属性设置为absolute并将top设置为50% 现在不再使用负边距来真正居中子元素,只需使用transform: translate(0, -50%)

HTML

<div class="container">
  <div class="child"></div>
</div>

CSS

.container {
  font-family: arial;
  font-size: 24px;
  margin: 25px;
  width: 350px;
  height: 200px;
  outline: dashed 1px black;
  /* Setup */
  position: relative;
}

.child {
  width: 50px;
  height: 50px;
  background-color: red;
  /* Center vertically */
  position: absolute;
  top: 50%;
  transform: translate(0, -50%);
}

请注意, translate(0, -50%)translateX(0)translateY(-50%)的简写。 您还可以编写transform: translateY(-50%)以使子元素垂直center

垂直和水平居中

使用 CSS 绝对定位和负边距使 Div 垂直和水平居中

这与上面将元素垂直居中的方法非常相似。 和上次一样,你必须知道你想要居中的元素的宽度和高度。

将父元素的position属性设置为relative

然后将孩子的position属性设置为 absolute, top设置为50%left设置为50% 这只是将子元素的左上角垂直和水平居中。

要使子元素真正居中,请将负上外边距设置为子元素高度的一半,并将负左外边距设置为子元素宽度的一半:

HTML

<div class="container">
  <div class="child"></div>
</div>

CSS

.container {
  font-family: arial;
  font-size: 24px;
  margin: 25px;
  width: 350px;
  height: 200px;
  outline: dashed 1px black;
  /* Setup */
  position: relative;
}

.child {
  width: 50px;
  height: 50px;
  background-color: red;
  /* Center vertically and horizontally */
  position: absolute;
  top: 50%;
  left: 50%;
  margin: -25px 0 0 -25px; /* Apply negative top and left margins to truly center the element */
}

要垂直对齐网页中的框,包括 Internet Explorer 6,您可以使用:

  1. 有条件的评论
  2. haslayout属性
  3. display: table-value其他人的display: table-value (现在是flex)

小提琴

 /* Internet Explorer 8 and others */ .main { width: 500px; margin: auto; border: solid; } html { height: 100%; width: 100%; display: table; } body { display: table-cell; vertical-align: middle; }
 <!-- [if lte IE 7]> <style> /* Should be in the <head> */ html, body , .ie { height: 100%; text-align: center; white-space: nowrap; } .ie , .main{ display: inline; /* Used with zoom in case you take a block element instead an inline element */ zoom: 1; vertical-align: middle; text-align: left; white-space: normal; } </style> <b class="ie"></b> <!--[endif]--> <div class="main"> <p>Fill it up with your content </p> <p><a href="https://jsfiddle.net/h8z24s5v/embedded/result/">JsFiddle versie</a></p> </div>

实际上,Internet Explorer 7 会带来一些麻烦,因为它是唯一严格应用height: 100% HTML/body 元素的版本。


但是,这是过去和今天,谁仍然介意旧版本的 Internet Explorer, table/table-cell很好, display: flex很有前途,而display: grid总有一天会出现。


另一个现在通过 flex 的例子

 html { display: flex; min-height: 100vh;/* or height */ } body { margin: auto; }
 <div>Div to be aligned vertically</div>

这是一个简单的方法,几乎​​没有代码:

CSS代码:

.main{
    height: 100%;
}

.center{
    top: 50%;
    margin-top: 50%;
}

HTML代码:

<div class="main">
    <div class="center">
        Hi, I am centered!
    </div>
</div>

您的文字将位于页面中间!

这在我的情况下有效(仅在现代浏览器中测试):

.textthatneedstobecentered {
  margin: auto;
  top: 0; bottom: 0;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM