居中的最佳方式 在页面上垂直和水平?

发布于 2024-07-11 05:49:53 字数 154 浏览 8 评论 0原文

元素在页面上垂直和水平居中的最佳方法是什么?

我知道 margin-left: auto; margin-right: auto; 将在水平方向上居中,但是在垂直方向上居中的最佳方法是什么?

Best way to center a <div> element on a page both vertically and horizontally?

I know that margin-left: auto; margin-right: auto; will center on the horizontal, but what is the best way to do it vertically, too?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(30

A君 2024-07-18 05:49:54

其实有一个解决方案,使用css3,可以将未知高度的div垂直居中。 诀窍是将 div 向下移动 50%,然后使用 transformY 将其恢复到中间。 唯一的先决条件是要居中的元素有一个父元素。 示例:

<div class="parent">
    <div class="center-me">
        Text, images, whatever suits you.
    </div>
</div>

.parent { 
    /* height can be whatever you want, also auto if you want a child 
       div to be responsible for the sizing */ 
    height: 200px;
}

.center-me { 
    position: relative;
    top: 50%;
    transform: translateY(-50%);
    /* prefixes needed for cross-browser support */
    -ms-transform: translateY(-50%);
    -webkit-transform: translateY(-50%);
}

受所有主流浏览器以及 IE 9 及更高版本支持(不必担心 IE 8,因为它在今年秋天与 win xp 一起消亡。感谢上帝。)

JS Fiddle 演示

There is actually a solution, using css3, which can vertically center a div of unknown height. The trick is to move the div down by 50%, then use transformY to get it back up to the middle. The only prerequisite is that the to-be-centered element has a parent. Example:

<div class="parent">
    <div class="center-me">
        Text, images, whatever suits you.
    </div>
</div>

.parent { 
    /* height can be whatever you want, also auto if you want a child 
       div to be responsible for the sizing */ 
    height: 200px;
}

.center-me { 
    position: relative;
    top: 50%;
    transform: translateY(-50%);
    /* prefixes needed for cross-browser support */
    -ms-transform: translateY(-50%);
    -webkit-transform: translateY(-50%);
}

Supported by all major browsers, and IE 9 and up (don't bother about IE 8, as it died together with win xp this autumn. Thank god.)

JS Fiddle Demo

被翻牌 2024-07-18 05:49:54

解决方案

仅使用两行CSS,利用Flexbox的神奇力量

.parent { display: flex; }
.child { margin: auto }

Solution

Using only two lines of CSS, utilizing the magical power of Flexbox

.parent { display: flex; }
.child { margin: auto }
反话 2024-07-18 05:49:54

另一种方法(防弹)取自此处< /a> 利用“display:table”规则:

标记

<div class="container">
  <div class="outer">
    <div class="inner">
      <div class="centered">
        ...
      </div>
    </div>
  </div>
</div>

CSS:

.outer {
  display: table;
  width: 100%;
  height: 100%;
}
.inner {
  display: table-cell;
  vertical-align: middle;
  text-align: center;
}
.centered {
  position: relative;
  display: inline-block;

  width: 50%;
  padding: 1em;
  background: orange;
  color: white;
}

One more method (bulletproof) taken from here utilizing 'display:table' rule:

Markup

<div class="container">
  <div class="outer">
    <div class="inner">
      <div class="centered">
        ...
      </div>
    </div>
  </div>
</div>

CSS:

.outer {
  display: table;
  width: 100%;
  height: 100%;
}
.inner {
  display: table-cell;
  vertical-align: middle;
  text-align: center;
}
.centered {
  position: relative;
  display: inline-block;

  width: 50%;
  padding: 1em;
  background: orange;
  color: white;
}
风筝在阴天搁浅。 2024-07-18 05:49:54

我正在查看 Laravel 的视图文件,注意到它们将文本完美地居中在中间。 我立刻就想起了这个问题。
他们是这样做的:

<html>
<head>
    <title>Laravel</title>

    <!--<link href='//fonts.googleapis.com/css?family=Lato:100' rel='stylesheet' type='text/css'>-->

    <style>
        .container {
            margin: 0;
            padding: 0;
            width: 100%;
            height: 100%;
            display: table;

        }

        .inside {
            text-align: center;
            display: table-cell;
            vertical-align: middle;
        }


    </style>
</head>
<body>
    <div class="container">
            <div class="inside">This text is centered</div>
    </div>
</body>

结果看起来像这样:

在此处输入图像描述

I was looking at Laravel's view file and noticed that they centered text perfectly in the middle. I remembered about this question immediately.
This is how they did it:

<html>
<head>
    <title>Laravel</title>

    <!--<link href='//fonts.googleapis.com/css?family=Lato:100' rel='stylesheet' type='text/css'>-->

    <style>
        .container {
            margin: 0;
            padding: 0;
            width: 100%;
            height: 100%;
            display: table;

        }

        .inside {
            text-align: center;
            display: table-cell;
            vertical-align: middle;
        }


    </style>
</head>
<body>
    <div class="container">
            <div class="inside">This text is centered</div>
    </div>
</body>

Result looks so:

enter image description here

反话 2024-07-18 05:49:54

另一种答案是这个

<div id="container"> 
    <div id="centered"> </div>
</div>

和CSS:

#container {
    height: 400px;
    width: 400px;
    background-color: lightblue;
    text-align: center;
}

#container:before {
    height: 100%;
    content: '';
    display: inline-block;
    vertical-align: middle;
}

#centered {
    width: 100px;
    height: 100px;
    background-color: blue;
    display: inline-block;
    vertical-align: middle;
    margin: 0 auto;
}

An alternative answer would be this.

<div id="container"> 
    <div id="centered"> </div>
</div>

and the css:

#container {
    height: 400px;
    width: 400px;
    background-color: lightblue;
    text-align: center;
}

#container:before {
    height: 100%;
    content: '';
    display: inline-block;
    vertical-align: middle;
}

#centered {
    width: 100px;
    height: 100px;
    background-color: blue;
    display: inline-block;
    vertical-align: middle;
    margin: 0 auto;
}
鹿港小镇 2024-07-18 05:49:54

我很惊讶这一点还没有被提及,但最简单的方法是使用视口大小设置高度、边距(和宽度,如果需要的话)。
您可能知道,视口的总高度 = 100vh。
假设您希望容器的高度占据屏幕的 60% (60vh),您可以在顶部和底部边距之间平均划分其余部分 (40vh),以便元素在屏幕中自行对齐自动居中。
margin-leftmargin-right 设置为 auto 将确保容器水平居中。

.container {
         width: 60vw; /*optional*/
         height: 60vh;
         margin: 20vh auto;
         background: #333;
 }
<div class="container">
</div>

I'm surprised this has not been mentioned yet, but the simplest way to do this would be by setting the height, margin (and width, if you want) using viewport sizes.
As you might know, total height of the viewport = 100vh.
Say you want the height of you container to occupy 60% (60vh) of the screen, you can divide the rest (40vh) equally between the top and the bottom margin so that the element aligns itself in the centre automatically.
Setting the margin-left and margin-right to auto, will make sure the container is centred horizontally.

.container {
         width: 60vw; /*optional*/
         height: 60vh;
         margin: 20vh auto;
         background: #333;
 }
<div class="container">
</div>

分開簡單 2024-07-18 05:49:54

如果您知道 div 的定义大小,您可以使用 calc

实例: https://jsfiddle.net/o8416eq3/

注意:仅当您对宽度进行硬编码时才有效以及 CSS 中“div”的高度。

#target {
  position:fixed;
  top: calc(50vh - 100px/2);
  left: calc(50vw - 200px/2);
  width:200px;
  height:100px;
  background-color:red;
}
<div id='target'></div>

In case you know a defined sized for your div you could use calc.

Live example: https://jsfiddle.net/o8416eq3/

Notes: This works only if you hard coded the width and height of your ``div` in the CSS.

#target {
  position:fixed;
  top: calc(50vh - 100px/2);
  left: calc(50vw - 200px/2);
  width:200px;
  height:100px;
  background-color:red;
}
<div id='target'></div>

月牙弯弯 2024-07-18 05:49:54

在父级上使用 display:grid 并将 margin:auto 设置为 centerrd 元素即可解决问题:

请参阅下面的代码片段:

html,body {
  width :100%;
  height:100%;
  margin:0;
  padding:0;
}

.container {
  display:grid;
  height:90%;
  background-color:blue;
}

.content {
  margin:auto;
  color:white;
}
<div class="container">
  <div class="content"> cented div  here</div>
</div>

Using display:grid on parent and setting margin:auto to the centrerd elemnt will do the trick :

See below snippet :

html,body {
  width :100%;
  height:100%;
  margin:0;
  padding:0;
}

.container {
  display:grid;
  height:90%;
  background-color:blue;
}

.content {
  margin:auto;
  color:white;
}
<div class="container">
  <div class="content"> cented div  here</div>
</div>

春夜浅 2024-07-18 05:49:54
div {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    -ms-transform: translate(-50%, -50%); /* IE 9 */
    -webkit-transform: translate(-50%, -50%); /* Chrome, Safari, Opera */	    
}
<body>
    <div>Div to be aligned vertically</div>
</body>

position:absolute div in body document

具有position:absolute的元素; 相对于最近定位的祖先定位(而不是相对于视口(body 标记)定位,如固定)。

然而; 如果绝对定位的元素没有定位的祖先,则它使用文档主体,并随着页面滚动而移动。

来源: CSS 位置

div {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    -ms-transform: translate(-50%, -50%); /* IE 9 */
    -webkit-transform: translate(-50%, -50%); /* Chrome, Safari, Opera */	    
}
<body>
    <div>Div to be aligned vertically</div>
</body>

position: absolute div in body document

An element with position: absolute; is positioned relative to the nearest positioned ancestor (instead of positioned relative to the viewport (body tag), like fixed).

However; if an absolute positioned element has no positioned ancestors, it uses the document body, and moves along with page scrolling.

source: CSS position

清晰传感 2024-07-18 05:49:54

如果你们使用 JQuery,则可以使用 .position(); 来完成此操作。

<div class="positionthis"></div>

CSS

.positionthis {
    width:100px;
    height:100px;
    position: absolute;
    background:blue;
}

Javascript (JQuery)

$(document).ready(function () {
    $('.positionthis').position({
        of: $(document),
        my: 'center center',
        at: 'center center',
        collision: 'flip flip'
    });
});

JSFiddle : http://jsfiddle.net/vx9gV/

If you guys are using JQuery, you can do this by using .position();

<div class="positionthis"></div>

CSS

.positionthis {
    width:100px;
    height:100px;
    position: absolute;
    background:blue;
}

Javascript (JQuery)

$(document).ready(function () {
    $('.positionthis').position({
        of: $(document),
        my: 'center center',
        at: 'center center',
        collision: 'flip flip'
    });
});

JSFiddle : http://jsfiddle.net/vx9gV/

郁金香雨 2024-07-18 05:49:54

浏览器支持的话,用translate就厉害了。

position: absolute;
background-color: red;

width: 70%;     
height: 30%; 

/* The translate % is relative to the size of the div and not the container*/ 
/* 21.42% = ( (100%-70%/2) / 0.7 ) */
/* 116.666% = ( (100%-30%/2) / 0.3 ) */
transform: translate3d( 21.42%, 116.666%, 0);

Is the browser supports it, using translate is powerful.

position: absolute;
background-color: red;

width: 70%;     
height: 30%; 

/* The translate % is relative to the size of the div and not the container*/ 
/* 21.42% = ( (100%-70%/2) / 0.7 ) */
/* 116.666% = ( (100%-30%/2) / 0.3 ) */
transform: translate3d( 21.42%, 116.666%, 0);
⒈起吃苦の倖褔 2024-07-18 05:49:54

抱歉回复晚了
最好的方法是

  div {
      position: fixed;
      top: 50%;
      left: 50%;
      margin-top: -50px;
      margin-left: -100px;
    }

margin-top 和 margin-left 应根据您的 div 框大小

Sorry for late reply
best way is

  div {
      position: fixed;
      top: 50%;
      left: 50%;
      margin-top: -50px;
      margin-left: -100px;
    }

margin-top and margin-left should be according to your div box size

飘然心甜 2024-07-18 05:49:54

请使用以下 CSS 属性来水平和垂直居中对齐元素。 这对我来说效果很好。

div {
  position: absolute;
  left: 0;
  top: 0;
  right: 0;
  bottom: 0px;
  margin: auto;
  width: 100px;
  height: 100px;
}

Please use following CSS properties for center align element horizontally as well as vertically. This is worked fine for me.

div {
  position: absolute;
  left: 0;
  top: 0;
  right: 0;
  bottom: 0px;
  margin: auto;
  width: 100px;
  height: 100px;
}
日记撕了你也走了 2024-07-18 05:49:54

这个解决方案对我有用

    .middleDiv{
        position : absolute;
        height : 90%;
        bottom: 5%;
    }

(或高度:70%/底部:15%

高度:40%/底部:30%......)

This solution worked for me

    .middleDiv{
        position : absolute;
        height : 90%;
        bottom: 5%;
    }

(or height : 70% / bottom : 15%

height : 40% / bottom :30% ...)

且行且努力 2024-07-18 05:49:53

最好、最灵活的方法

这个演示中的主要技巧是,在从上到下的正常元素流中,因此将 margin-top: auto 设置为零。 但是,绝对定位元素对于自由空间的分配具有相同的作用,并且类似地可以在指定的 topbottom 处垂直居中(在 IE7 中不起作用)。

##这个技巧适用于任何大小的 div

div {
    width: 100px;
    height: 100px;
    background-color: red;
    
    position: absolute;
    top:0;
    bottom: 0;
    left: 0;
    right: 0;
    
    margin: auto;
}
<div></div>

The best and most flexible way

The main trick in this demo is that in the normal flow of elements going from top to bottom, so the margin-top: auto is set to zero. However, an absolutely positioned element acts the same for distribution of free space, and similarly can be centered vertically at the specified top and bottom (does not work in IE7).

##This trick will work with any sizes of div.

div {
    width: 100px;
    height: 100px;
    background-color: red;
    
    position: absolute;
    top:0;
    bottom: 0;
    left: 0;
    right: 0;
    
    margin: auto;
}
<div></div>

顾挽 2024-07-18 05:49:53

尽管当OP提出这个问题时这不起作用,但我认为,至少对于现代浏览器来说,最好的解决方案是使用display:flex伪类

您可以在下面的 fiddle 中看到一个示例。
这是更新的小提琴

对于伪类,一个例子可以是:

.centerPseudo {
    display:inline-block;
    text-align:center;
}

.centerPseudo::before{
    content:'';
    display:inline-block;
    height:100%;
    vertical-align:middle;
    width:0px;
}

display: flex的使用,根据css-tricksMDN 如下:

.centerFlex {
  align-items: center;
  display: flex;
  justify-content: center;
}

还有其他可用于 flex 的属性,这些属性在上面提到的链接中进行了解释,并附有更多示例。

如果您必须支持不支持 css3 的旧版浏览器,那么您可能应该使用 javascript 或其他答案中显示的固定宽度/高度解决方案。

Even though this did not work when the OP asked this question, I think, for modern browsers at least, the best solution is to use display: flex or pseudo classes.

You can see an example in the following fiddle.
Here is the updated fiddle.

For pseudo classes an example could be:

.centerPseudo {
    display:inline-block;
    text-align:center;
}

.centerPseudo::before{
    content:'';
    display:inline-block;
    height:100%;
    vertical-align:middle;
    width:0px;
}

The usage of display: flex, according to css-tricks and MDN is as follows:

.centerFlex {
  align-items: center;
  display: flex;
  justify-content: center;
}

There are other attributes available for flex, which are explained in above mentioned links, with further examples.

If you have to support older browsers, which don't support css3, then you should probably use javascript or the fixed width/height solution shown in the other answers.

梦太阳 2024-07-18 05:49:53

这项技术的简单性令人惊叹:
(虽然这种方法有它的含义,但如果您只需要居中元素而不管其余内容的流动,那就没问题。小心使用)

标记:

<div>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum accumsan tellus purus, et mollis nulla consectetur ac. Quisque id elit at diam convallis venenatis eget sed justo. Nunc egestas enim mauris, sit amet tempor risus ultricies in. Sed dignissim magna erat, vel laoreet tortor bibendum vitae. Ut porttitor tincidunt est imperdiet vestibulum. Vivamus id nibh tellus. Integer massa orci, gravida non imperdiet sed, consectetur ac quam. Nunc dignissim felis id tortor tincidunt, a eleifend nulla molestie. Phasellus eleifend leo purus, vel facilisis massa dignissim vitae. Pellentesque libero sapien, tincidunt ut lorem non, porta accumsan risus. Morbi tempus pharetra ex, vel luctus turpis tempus eu. Integer vitae sagittis massa, id gravida erat. Maecenas sed purus et magna tincidunt faucibus nec eget erat. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc nec mollis sem.</div>

和 CSS:

div {
  color: white;
  background: red;
  padding: 15px;
  position: absolute;
  top: 50%;
  left: 50%;
  -ms-transform: translateX(-50%) translateY(-50%);
  -webkit-transform: translate(-50%,-50%);
  transform: translate(-50%,-50%);
}   

这也将使元素水平和垂直居中。 没有负边距,只有变换的力量。 而且我们应该已经忘记 IE8 不是吗?

Simplicity of this technique is stunning:
(This method has its implications though, but if you only need to center element regardless of flow of the rest of the content, it's just fine. Use with care)

Markup:

<div>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum accumsan tellus purus, et mollis nulla consectetur ac. Quisque id elit at diam convallis venenatis eget sed justo. Nunc egestas enim mauris, sit amet tempor risus ultricies in. Sed dignissim magna erat, vel laoreet tortor bibendum vitae. Ut porttitor tincidunt est imperdiet vestibulum. Vivamus id nibh tellus. Integer massa orci, gravida non imperdiet sed, consectetur ac quam. Nunc dignissim felis id tortor tincidunt, a eleifend nulla molestie. Phasellus eleifend leo purus, vel facilisis massa dignissim vitae. Pellentesque libero sapien, tincidunt ut lorem non, porta accumsan risus. Morbi tempus pharetra ex, vel luctus turpis tempus eu. Integer vitae sagittis massa, id gravida erat. Maecenas sed purus et magna tincidunt faucibus nec eget erat. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc nec mollis sem.</div>

And CSS:

div {
  color: white;
  background: red;
  padding: 15px;
  position: absolute;
  top: 50%;
  left: 50%;
  -ms-transform: translateX(-50%) translateY(-50%);
  -webkit-transform: translate(-50%,-50%);
  transform: translate(-50%,-50%);
}   

This will center element horizontally and vertically too. No negative margins, just power of transforms. Also we should already forget about IE8 shouldn't we?

孤单情人 2024-07-18 05:49:53

我会使用translate

首先将div的左上角定位在页面的中心(使用position:fixed;top:50%;left:50%)。 然后,translate 将其向上移动 div 高度的 50%,使其在页面上垂直居中。 最后,translate 还将 div 向右移动其宽度的 50%,使其水平居中。

实际上,我认为这种方法比许多其他方法更好,因为它不需要对父元素进行任何更改。

在某些场景下,translatetranslate3d 更好,因为它受到更多浏览器的支持。 https://caniuse.com/#feat=transforms2d

综上所述,该方法支持所有版本的 Chrome、Firefox 3.5+、Opera 11.5+、所有版本的 Safari、IE 9+ 和 Edge。

.centered {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  -webkit-transform: translate(-50%, -50%);
  -moz-transform: translate(-50%, -50%);
  -o-transform: translate(-50%, -50%);
  -ms-transform: translate(-50%, -50%);
  
  font-size: 20px;
  background-color: cyan;
  border: darkgreen 5px solid;
  padding: 5px;
  z-index: 100;
}

table {
    position: absolute;
    top: 0;
    left: 0;
}

td {
    position: relative;
    top: 0;
    left: 0;
}
<table>
<tr>
    <td>
        <div class="centered">This div<br />is centered</div>
        <p>
            Lorem ipsum dolor sit amet, nam sint laoreet at, his ne sumo causae, simul decore deterruisset ne mel. Exerci atomorum est ut. At choro vituperatoribus usu. Dico epicurei persequeris quo ex, ea ius zril phaedrum eloquentiam, duo in aperiam admodum fuisset. No quidam consequuntur usu, in amet hinc simul eos. Ex soleat meliore percipitur mea, nihil omittam salutandi ut eos. Mea et impedit facilisi pertinax, ea viris graeci fierent pri, te sonet intellegebat his. Vis denique albucius instructior ad, ex eum iudicabit elaboraret. Sit ea intellegam liberavisse. Nusquam quaestio maiestatis ut qui, eam decore altera te. Unum cibo aliquip ut qui, te mea doming prompta. Ex rebum interesset nam, te nam zril suscipit, qui suavitate explicari appellantur te. Usu brute corpora mandamus eu. Dicit soluta his eu. In sint consequat sed, quo ea tota petentium. Adhuc prompta splendide mel ad, soluta delenit nec cu.
        </p>
    </td>
    <td>
        <p>
            Lorem ipsum dolor sit amet, dico choro recteque te cum, ex omnesque consectetuer sed, alii esse utinam et has. An qualisque democritum usu. Ea has habeo labores, laoreet intellegat te mea. Eius equidem inermis vel ne. Ne eum sonet labitur, nec id natum munere. Primis graecis est cu, quis dictas eu mea, eu quem offendit forensibus nec. Id animal mandamus his, vis in sonet tempor luptatum. Ne civibus oporteat comprehensam vix, per facete discere atomorum eu. Mucius probatus volutpat sit an, sumo nominavi democritum eam ut. Ea sit choro graece debitis, per ex verear voluptua epicurei. Id eum wisi dicat, ea sit velit doming cotidieque, eu sea amet delenit. Populo tacimates dissentiunt has cu. Has wisi hendrerit at, et quo doming putent docendi. Ea nibh vide omnium usu.
        </p>
    </td>
</tr>
</table>

但请注意,此方法使该 div 在页面滚动时停留在一个位置。 这可能是您想要的,但如果不是,还有另一种方法。

现在,如果我们尝试相同的 CSS,但将位置设置为绝对,它将位于具有绝对位置的最后一个父级的中心。

.centered {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  -webkit-transform: translate(-50%, -50%);
  -moz-transform: translate(-50%, -50%);
  -o-transform: translate(-50%, -50%);
  -ms-transform: translate(-50%, -50%);

  font-size: 20px;
  background-color: cyan;
  border: darkgreen 5px solid;
  padding: 5px;
  z-index: 100;
}

table {
    position: absolute;
    top: 0;
    left: 0;
}

td {
    position: relative;
    top: 0;
    left: 0;
}
<table>
<tr>
    <td>
        <div class="centered">This div<br />is centered</div>
        <p>
            Lorem ipsum dolor sit amet, nam sint laoreet at, his ne sumo causae, simul decore deterruisset ne mel. Exerci atomorum est ut. At choro vituperatoribus usu. Dico epicurei persequeris quo ex, ea ius zril phaedrum eloquentiam, duo in aperiam admodum fuisset. No quidam consequuntur usu, in amet hinc simul eos. Ex soleat meliore percipitur mea, nihil omittam salutandi ut eos. Mea et impedit facilisi pertinax, ea viris graeci fierent pri, te sonet intellegebat his. Vis denique albucius instructior ad, ex eum iudicabit elaboraret. Sit ea intellegam liberavisse. Nusquam quaestio maiestatis ut qui, eam decore altera te. Unum cibo aliquip ut qui, te mea doming prompta. Ex rebum interesset nam, te nam zril suscipit, qui suavitate explicari appellantur te. Usu brute corpora mandamus eu. Dicit soluta his eu. In sint consequat sed, quo ea tota petentium. Adhuc prompta splendide mel ad, soluta delenit nec cu.
        </p>
    </td>
    <td>
        <p>
            Lorem ipsum dolor sit amet, dico choro recteque te cum, ex omnesque consectetuer sed, alii esse utinam et has. An qualisque democritum usu. Ea has habeo labores, laoreet intellegat te mea. Eius equidem inermis vel ne. Ne eum sonet labitur, nec id natum munere. Primis graecis est cu, quis dictas eu mea, eu quem offendit forensibus nec. Id animal mandamus his, vis in sonet tempor luptatum. Ne civibus oporteat comprehensam vix, per facete discere atomorum eu. Mucius probatus volutpat sit an, sumo nominavi democritum eam ut. Ea sit choro graece debitis, per ex verear voluptua epicurei. Id eum wisi dicat, ea sit velit doming cotidieque, eu sea amet delenit. Populo tacimates dissentiunt has cu. Has wisi hendrerit at, et quo doming putent docendi. Ea nibh vide omnium usu.
        </p>
    </td>
</tr>
</table>

I would use translate:

First position the div's top left corner at the center of the page (using position: fixed; top: 50%; left: 50%). Then, translate moves it up by 50% of the div's height to center it vertically on the page. Finally, translate also moves the div to the right by 50% of it's width to center it horizontally.

I actually think that this method is better than many of the others, since it does not require any changes on the parent element.

translate is better than translate3d in some scenarios due to it being supported by a greater number of browsers. https://caniuse.com/#feat=transforms2d

To sum it up, this method is supported on all versions of Chrome, Firefox 3.5+, Opera 11.5+, all versions of Safari, IE 9+, and Edge.

.centered {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  -webkit-transform: translate(-50%, -50%);
  -moz-transform: translate(-50%, -50%);
  -o-transform: translate(-50%, -50%);
  -ms-transform: translate(-50%, -50%);
  
  font-size: 20px;
  background-color: cyan;
  border: darkgreen 5px solid;
  padding: 5px;
  z-index: 100;
}

table {
    position: absolute;
    top: 0;
    left: 0;
}

td {
    position: relative;
    top: 0;
    left: 0;
}
<table>
<tr>
    <td>
        <div class="centered">This div<br />is centered</div>
        <p>
            Lorem ipsum dolor sit amet, nam sint laoreet at, his ne sumo causae, simul decore deterruisset ne mel. Exerci atomorum est ut. At choro vituperatoribus usu. Dico epicurei persequeris quo ex, ea ius zril phaedrum eloquentiam, duo in aperiam admodum fuisset. No quidam consequuntur usu, in amet hinc simul eos. Ex soleat meliore percipitur mea, nihil omittam salutandi ut eos. Mea et impedit facilisi pertinax, ea viris graeci fierent pri, te sonet intellegebat his. Vis denique albucius instructior ad, ex eum iudicabit elaboraret. Sit ea intellegam liberavisse. Nusquam quaestio maiestatis ut qui, eam decore altera te. Unum cibo aliquip ut qui, te mea doming prompta. Ex rebum interesset nam, te nam zril suscipit, qui suavitate explicari appellantur te. Usu brute corpora mandamus eu. Dicit soluta his eu. In sint consequat sed, quo ea tota petentium. Adhuc prompta splendide mel ad, soluta delenit nec cu.
        </p>
    </td>
    <td>
        <p>
            Lorem ipsum dolor sit amet, dico choro recteque te cum, ex omnesque consectetuer sed, alii esse utinam et has. An qualisque democritum usu. Ea has habeo labores, laoreet intellegat te mea. Eius equidem inermis vel ne. Ne eum sonet labitur, nec id natum munere. Primis graecis est cu, quis dictas eu mea, eu quem offendit forensibus nec. Id animal mandamus his, vis in sonet tempor luptatum. Ne civibus oporteat comprehensam vix, per facete discere atomorum eu. Mucius probatus volutpat sit an, sumo nominavi democritum eam ut. Ea sit choro graece debitis, per ex verear voluptua epicurei. Id eum wisi dicat, ea sit velit doming cotidieque, eu sea amet delenit. Populo tacimates dissentiunt has cu. Has wisi hendrerit at, et quo doming putent docendi. Ea nibh vide omnium usu.
        </p>
    </td>
</tr>
</table>

Notice, however, that this method makes this div stay in one place while the page is being scrolled. This may be what you want but if not, there is another method.

Now, if we try the same CSS, but with position set to absolute, it will be in the center of the last parent that has an absolute position.

.centered {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  -webkit-transform: translate(-50%, -50%);
  -moz-transform: translate(-50%, -50%);
  -o-transform: translate(-50%, -50%);
  -ms-transform: translate(-50%, -50%);

  font-size: 20px;
  background-color: cyan;
  border: darkgreen 5px solid;
  padding: 5px;
  z-index: 100;
}

table {
    position: absolute;
    top: 0;
    left: 0;
}

td {
    position: relative;
    top: 0;
    left: 0;
}
<table>
<tr>
    <td>
        <div class="centered">This div<br />is centered</div>
        <p>
            Lorem ipsum dolor sit amet, nam sint laoreet at, his ne sumo causae, simul decore deterruisset ne mel. Exerci atomorum est ut. At choro vituperatoribus usu. Dico epicurei persequeris quo ex, ea ius zril phaedrum eloquentiam, duo in aperiam admodum fuisset. No quidam consequuntur usu, in amet hinc simul eos. Ex soleat meliore percipitur mea, nihil omittam salutandi ut eos. Mea et impedit facilisi pertinax, ea viris graeci fierent pri, te sonet intellegebat his. Vis denique albucius instructior ad, ex eum iudicabit elaboraret. Sit ea intellegam liberavisse. Nusquam quaestio maiestatis ut qui, eam decore altera te. Unum cibo aliquip ut qui, te mea doming prompta. Ex rebum interesset nam, te nam zril suscipit, qui suavitate explicari appellantur te. Usu brute corpora mandamus eu. Dicit soluta his eu. In sint consequat sed, quo ea tota petentium. Adhuc prompta splendide mel ad, soluta delenit nec cu.
        </p>
    </td>
    <td>
        <p>
            Lorem ipsum dolor sit amet, dico choro recteque te cum, ex omnesque consectetuer sed, alii esse utinam et has. An qualisque democritum usu. Ea has habeo labores, laoreet intellegat te mea. Eius equidem inermis vel ne. Ne eum sonet labitur, nec id natum munere. Primis graecis est cu, quis dictas eu mea, eu quem offendit forensibus nec. Id animal mandamus his, vis in sonet tempor luptatum. Ne civibus oporteat comprehensam vix, per facete discere atomorum eu. Mucius probatus volutpat sit an, sumo nominavi democritum eam ut. Ea sit choro graece debitis, per ex verear voluptua epicurei. Id eum wisi dicat, ea sit velit doming cotidieque, eu sea amet delenit. Populo tacimates dissentiunt has cu. Has wisi hendrerit at, et quo doming putent docendi. Ea nibh vide omnium usu.
        </p>
    </td>
</tr>
</table>

暮色兮凉城 2024-07-18 05:49:53

我认为使用 Flex-box:

#parent {
  display: flex;
  justify-content: center;
  align-items: center;
}
<div id="parent">
  <div id="child">Hello World!</div>
</div>

您会看到,只需使用三个 CSS 属性即可使子元素垂直和水平居中。 display: flex; 通过激活 Flex-box 显示来完成主要部分,justify-content: center; 使子元素垂直居中,align-items: center ; 将其水平居中。 为了看到最好的结果,我只需添加一些额外的样式:

#parent {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 500px;
  width: 500px;
  background: yellow;
}

#child {
  width: 100px;
  height: 100px;
  background: silver;
}
<div id="parent">
  <div id="child">Hello World!</div>
</div>

如果您想了解有关 Flex-box 的更多信息,可以访问 W3SchoolsMDNCSS-Tricks 了解更多信息。

Using Flex-box in my opinion:

#parent {
  display: flex;
  justify-content: center;
  align-items: center;
}
<div id="parent">
  <div id="child">Hello World!</div>
</div>

You see there are only three CSS properties that you have to use to center the child element vertically and horizontally. display: flex; Do the main part by just activating Flex-box display, justify-content: center; center the child element vertically and align-items: center; center it horizontally. To see the best result I just add some extra styles :

#parent {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 500px;
  width: 500px;
  background: yellow;
}

#child {
  width: 100px;
  height: 100px;
  background: silver;
}
<div id="parent">
  <div id="child">Hello World!</div>
</div>

If you want to learn more about Flex-box you can visit W3Schools, MDN or CSS-Tricks for more information.

请止步禁区 2024-07-18 05:49:53

利用 Flex Display 的简单解决方案

 <div style = 'display:flex; position:absolute; top:0; bottom:0; right:0; left:0; '>
      <div id = 'div_you_want_centered' style = 'margin:auto;'> 
           This will be Centered 
      </div>
 </div>

查看 http://css-tricks .com/snippets/css/a-guide-to-flexbox/

第一个 div 占据整个屏幕,并为每个浏览器设置了 display:flex 。 第二个 div(居中 div)利用了 display:flex div,其中 margin:auto 表现出色。

注意 IE11+ 兼容性。 (IE10 带前缀)。

Simple solution taking advantage of Flex Display

 <div style = 'display:flex; position:absolute; top:0; bottom:0; right:0; left:0; '>
      <div id = 'div_you_want_centered' style = 'margin:auto;'> 
           This will be Centered 
      </div>
 </div>

Check out http://css-tricks.com/snippets/css/a-guide-to-flexbox/

The first div takes up the whole screen and has a display:flex set for every browser. The second div (centered div) takes advantage of the display:flex div where margin:auto works brilliantly.

Note IE11+ compatibility. (IE10 w/ prefix).

一笑百媚生 2024-07-18 05:49:53

我认为通过 CSS 使 div 居中对齐有两种方法。

.middleDiv {
    position : absolute;    
    width    : 200px;
    height   : 200px;
    left     : 50%;
    top      : 50%;
    margin-left : -100px; /* half of the width  */
    margin-top  : -100px; /* half of the height */
}

这是最简单也是最好的方法。 有关演示,请访问以下链接:

http:// /w3webpro.blogspot.in/2013/07/how-to-make-div-horizo​​ntally-and.html

I think there are two ways to make a div center align through CSS.

.middleDiv {
    position : absolute;    
    width    : 200px;
    height   : 200px;
    left     : 50%;
    top      : 50%;
    margin-left : -100px; /* half of the width  */
    margin-top  : -100px; /* half of the height */
}

This is the simple and best way. for the demo please visit below link:

http://w3webpro.blogspot.in/2013/07/how-to-make-div-horizontally-and.html

护你周全 2024-07-18 05:49:53

如果您正在使用新的浏览器(IE10+),

那么您可以利用transform属性将div居中对齐。

<div class="center-block">this is any div</div>

CSS 应该是:

.center-block {
  top:50%;
  left: 50%;
  transform: translate3d(-50%,-50%, 0);
  position: absolute;
}

这里的问题是你甚至不必指定 div 的高度和宽度,因为它会自行处理。

另外,如果您想将一个 div 定位在另一个 div 的中心,那么您只需将外部 div 的位置指定为 relative ,然后此 CSS 就开始为您的 div 工作。

工作原理

当您将 left 和 top 指定为 50% 时,div 会位于页面的右下四分之一,其左上角固定在页面的中心。
这是因为,左/上属性(当以 % 给出时)是根据外部 div 的高度(在您的情况下为窗口)计算的。

但是转换使用元素的高度/宽度来确定平移,因此您的 div 将向左移动(宽度的 50%)和顶部(高度的 50%),因为它们是以负数给出的,从而将其与页面的中心对齐。

如果您必须支持较旧的浏览器(抱歉,还包括 IE9),那么表格单元格是最流行的使用方法。

If you are looking at the new browsers(IE10+),

then you can make use of transform property to align a div at the center.

<div class="center-block">this is any div</div>

And css for this should be:

.center-block {
  top:50%;
  left: 50%;
  transform: translate3d(-50%,-50%, 0);
  position: absolute;
}

The catch here is that you don't even have to specify the height and width of the div as it takes care by itself.

Also, if you want to position a div at the center of another div, then you can just specify the position of outer div as relative and then this CSS starts working for your div.

How it works:

When you specify left and top at 50%, the div goes at the the bottom right quarter of the page with its top-left end pinned at the center of the page.
This is because, the left/top properties(when given in %) are calculated based on height of the outer div(in your case, window).

But transform uses height/width of the element to determine translation, so you div will move left(50% width) and top(50% its height) since they are given in negatives, thus aligning it to the center of the page.

If you have to support older browsers(and sorry including IE9 as well) then the table cell is most popular method to use.

つ低調成傷 2024-07-18 05:49:53

我最喜欢的将盒子垂直和水平居中的方法是以下技术:

外部容器

  • 应具有 display: table;

内部容器

  • 应具有 display: table-cell; >
  • 应该有 vertical-align: middle;
  • 应该有 text-align: center;

内容框

  • 应该有 display: inline-block;
  • 应该重新调整水平文本对齐方式,例如。 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">
        You can put anything here!
     </div>
   </div>
</div>

另请参阅这个小提琴


编辑

是的,我知道您可以使用 transform:translate(-50%, -50%);transform:translate3d(-50%,-50%) 实现或多或少相同的灵活性, 0);,我提出的技术具有更好的浏览器支持。 即使使用 -webkit-ms-moz 等浏览器前缀,transform 也无法提供完全相同的功能浏览器支持。

因此,如果您关心较旧的浏览器(例如 IE9 及以下版本),则不应使用 transform 进行定位。

My prefered way to center a box both vertically and horizontally, is the following technique :

The outer container

  • should have display: table;

The inner container

  • should have display: table-cell;
  • should have vertical-align: middle;
  • should have text-align: center;

The content box

  • should have display: inline-block;
  • should re-adjust the horizontal text-alignment to eg. text-align: left; or text-align: right;, unless you want text to be centered

The elegance of this technique, is that you can add your content to the content box without worrying about its height or width!

Demo

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">
        You can put anything here!
     </div>
   </div>
</div>

See also this Fiddle!


EDIT

Yes, I know you can achieve more or less the same flexibility with transform: translate(-50%, -50%); or transform: translate3d(-50%,-50%, 0);, the technique I'm proposing has far better browser support. Even with browsers prefixes like -webkit, -ms or -moz, transform doesn't offer quite the same browser support.

So if you care about older browsers (eg. IE9 and below), you should not use transform for positioning.

夏末染殇 2024-07-18 05:49:53
position: absolute;
left: 50%;
top: 50%;
-webkit-transform: translate(-50%, -50%);
-ms-transform: translate(-50%, -50%);
transform: translate(-50%, -50%);

说明:

给它一个绝对定位(父级应该有相对定位)。 然后,左上角移动到中心。 因为您还不知道宽度/高度,所以您使用 css 变换来相对于中间平移位置。 translate(-50%, -50%) 确实将左上角的 x 和 y 位置减少了 50% 的宽度和高度。

position: absolute;
left: 50%;
top: 50%;
-webkit-transform: translate(-50%, -50%);
-ms-transform: translate(-50%, -50%);
transform: translate(-50%, -50%);

Explanation:

Give it an absolute positioning (the parent should have relative positioning). Then, the upper left corner is moved to the center. Because you don't know the width/height yet, you use css transform to translate the position relatively to the middle. translate(-50%, -50%) does reduce the x and y position of the upper left corner by 50% of width and height.

成熟稳重的好男人 2024-07-18 05:49:53

这是我不久前编写的一个脚本(它是使用 jQuery 库编写的):

var centerIt = function (el /* (jQuery element) Element to center */) {
    if (!el) {
        return;
    }
    var moveIt = function () {
        var winWidth = $(window).width();
        var winHeight = $(window).height();
        el.css("position","absolute").css("left", ((winWidth / 2) - (el.width() / 2)) + "px").css("top", ((winHeight / 2) - (el.height() / 2)) + "px");
    }; 
    $(window).resize(moveIt);
    moveIt();
};

Here is a script i wrote a while back (it is written using the jQuery library):

var centerIt = function (el /* (jQuery element) Element to center */) {
    if (!el) {
        return;
    }
    var moveIt = function () {
        var winWidth = $(window).width();
        var winHeight = $(window).height();
        el.css("position","absolute").css("left", ((winWidth / 2) - (el.width() / 2)) + "px").css("top", ((winHeight / 2) - (el.height() / 2)) + "px");
    }; 
    $(window).resize(moveIt);
    moveIt();
};
零度° 2024-07-18 05:49:53

这是使 div 机器人水平和垂直居中的最佳代码

div
{
  position:absolute;
  top:50%;
  left:50%;
  transform:translate(-50%,-50%);
}

This is the best code to centre the div bot horizontally and vertically

div
{
  position:absolute;
  top:50%;
  left:50%;
  transform:translate(-50%,-50%);
}

闻呓 2024-07-18 05:49:53

2018 年使用 CSS 网格的方式:

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

检查浏览器支持,Caniuse 建议它适用于 Chrome 57、FF 52、Opera 44、Safari 10.1、Edge 16。我自己没有检查。

请参阅下面的片段:

.parent{
    display: grid;
    place-items: center center;
    /*place-items is a shorthand for align-items and justify-items*/
    
    height: 200px;
    border: 1px solid black;
    background: gainsboro;
}

.child{
    background: white;
}
<div class="parent">
    <div class="child">Centered!</div>
</div>

2018 way using CSS Grid:

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

Check for browser support, Caniuse suggests it works from Chrome 57, FF 52, Opera 44, Safari 10.1, Edge 16. I didn't check myself.

See snippet below:

.parent{
    display: grid;
    place-items: center center;
    /*place-items is a shorthand for align-items and justify-items*/
    
    height: 200px;
    border: 1px solid black;
    background: gainsboro;
}

.child{
    background: white;
}
<div class="parent">
    <div class="child">Centered!</div>
</div>

千纸鹤带着心事 2024-07-18 05:49:53

我知道我迟到了,但这里有一种方法可以将未知尺寸的 div 置于未知尺寸的父级中。

样式:

<style>

    .table {
      display: table;
      height: 100%;
      margin: 0 auto;
    }
    .table-cell {
      display: table-cell;
      vertical-align: middle;      
    }
    .centered {
      background-color: red;
    }
  </style>

HTML:

<div class="table">
    <div class="table-cell"><div class="centered">centered</div></div>
</div>

演示:

查看此演示

I know I am late to the party but here is a way to center a div with unknown dimension inside a parent of unknown dimension.

style:

<style>

    .table {
      display: table;
      height: 100%;
      margin: 0 auto;
    }
    .table-cell {
      display: table-cell;
      vertical-align: middle;      
    }
    .centered {
      background-color: red;
    }
  </style>

HTML:

<div class="table">
    <div class="table-cell"><div class="centered">centered</div></div>
</div>

DEMO:

Check out this demo.

墟烟 2024-07-18 05:49:53

虽然我来晚了,但这非常容易和简单。 页面中心始终保留 50%,顶部 50%。 所以减去div宽度和高度50%并设置左边距和右边距。 希望它适用于任何地方 -

body{
  background: #EEE;
}
.center-div{
  position: absolute;
  width: 200px;
  height: 60px;
  left: 50%;  
  margin-left: -100px;
  top: 50%;
  margin-top: -30px;
  background: #CCC;
  color: #000;
  text-align: center;
}
<div class="center-div">
  <h3>This is center div</h3>
</div>

Though I'm too late, but this is very easy and simple. Page center is always left 50%, and top 50%. So minus the div width and height 50% and set left margin and right margin. Hope it work's for everywhere -

body{
  background: #EEE;
}
.center-div{
  position: absolute;
  width: 200px;
  height: 60px;
  left: 50%;  
  margin-left: -100px;
  top: 50%;
  margin-top: -30px;
  background: #CCC;
  color: #000;
  text-align: center;
}
<div class="center-div">
  <h3>This is center div</h3>
</div>

八巷 2024-07-18 05:49:53
div {
    border-style: solid;
    position: fixed;
    width: 80%;
    height: 80%;
    left: 10%;
    top: 10%;
}

相对于宽度和高度调整left和top,即(100% - 80%) / 2 = 10%

div {
    border-style: solid;
    position: fixed;
    width: 80%;
    height: 80%;
    left: 10%;
    top: 10%;
}

Adjust left and top with respect to width and height, that is (100% - 80%) / 2 = 10%

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文