简体   繁体   English

如何水平居中元素?

[英]How can I horizontally center an element?

How can I horizontally center a <div> within another <div> using CSS?如何使用 CSS 将一个<div>在另一个<div>中水平居中?

<div id="outer">
  <div id="inner">Foo foo</div>
</div>

You can apply this CSS to the inner <div> :您可以将此 CSS 应用于内部<div>

#inner {
  width: 50%;
  margin: 0 auto;
}

Of course, you don't have to set the width to 50% .当然,您不必将width设置为50% Any width less than the containing <div> will work.任何小于包含<div>的宽度都可以。 The margin: 0 auto is what does the actual centering. margin: 0 auto是实际居中的位置。

If you are targeting Internet Explorer 8 (and later), it might be better to have this instead:如果您的目标是Internet Explorer 8 (及更高版本),则最好改为:

#inner {
  display: table;
  margin: 0 auto;
}

It will make the inner element center horizontally and it works without setting a specific width .它将使内部元素水平居中,并且无需设置特定width即可工作。

Working example here:这里的工作示例:

 #inner { display: table; margin: 0 auto; border: 1px solid black; } #outer { border: 1px solid red; width:100% }
 <div id="outer"> <div id="inner">Foo foo</div> </div>


EDIT编辑

With flexbox it is very easy to style the div horizontally and vertically centered.使用flexbox可以很容易地设置 div 水平和垂直居中的样式。

 #inner { border: 0.05em solid black; } #outer { border: 0.05em solid red; width:100%; display: flex; justify-content: center; }
 <div id="outer"> <div id="inner">Foo foo</div> </div>

To align the div vertically centered, use the property align-items: center .要使 div 垂直居中对齐,请使用属性align-items: center

If you don't want to set a fixed width on the inner div you could do something like this:如果您不想在内部div上设置固定宽度,您可以执行以下操作:

 #outer { width: 100%; text-align: center; } #inner { display: inline-block; }
 <div id="outer"> <div id="inner">Foo foo</div> </div>

That makes the inner div into an inline element that can be centered with text-align .这使得内部div成为可以使用text-align居中的内联元素。

The best approaches are with CSS3.最好的方法是使用 CSS3。

The old box model (deprecated)旧盒子模型(已弃用)

display: box and its properties box-pack , box-align , box-orient , box-direction etc. have been replaced by flexbox. display: box及其属性box-packbox-alignbox-orientbox-direction等已被 flexbox 取代。 While they may still work, they are not recommended to be used in production.虽然它们可能仍然有效,但不建议在生产中使用它们。

 #outer { width: 100%; /* Firefox */ display: -moz-box; -moz-box-pack: center; -moz-box-align: center; /* Safari and Chrome */ display: -webkit-box; -webkit-box-pack: center; -webkit-box-align: center; /* W3C */ display: box; box-pack: center; box-align: center; } #inner { width: 50%; }
 <div id="outer"> <div id="inner">Foo foo</div> </div>

According to your usability you may also use the box-orient, box-flex, box-direction properties.根据您的可用性,您还可以使用box-orient, box-flex, box-direction属性。

The modern box model with Flexbox带有 Flexbox 的现代盒子模型

#outer {
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;
    justify-content: center;
    align-items: center;
}

Read more about centering the child elements阅读有关使子元素居中的更多信息

And this explains why the box model is the best approach :这解释了为什么盒子模型是最好的方法

 #centered { position: absolute; left: 50%; margin-left: -100px; }
 <div id="outer" style="width:200px"> <div id="centered">Foo foo</div> </div>

Make sure the parent element is positioned , ie, relative, fixed, absolute, or sticky.确保父元素是定位的,即相对的、固定的、绝对的或粘性的。

If you don't know the width of your div, you can use transform:translateX(-50%);如果你不知道你的 div 的宽度,你可以使用transform:translateX(-50%); instead of the negative margin.而不是负边距。

With CSS calc() , the code can get even simpler:使用CSS calc() ,代码可以变得更加简单:


.centered {
  width: 200px;
  position: absolute;
  left: calc(50% - 100px);
}

The principle is still the same;原理还是一样的; put the item in the middle and compensate for the width.将物品放在中间并补偿宽度。

I've created this example to show how to vertically and horizontally align .我创建了这个示例来展示如何垂直水平align .

The code is basically this:代码基本上是这样的:

#outer {
 position: relative;
}

and...和...

#inner {
  margin: auto;
  position: absolute;
  left:0;
  right: 0;
  top: 0;
  bottom: 0;
}

And it will stay in the center even when you resize your screen.即使您调整屏幕大小,它也会保持在center

Some posters have mentioned the CSS 3 way to center using display:box .一些张贴者提到了使用display:box居中的 CSS 3 方式。

This syntax is outdated and shouldn't be used anymore.此语法已过时,不应再使用。 [See also this post] . [另见这篇文章]

So just for completeness here is the latest way to center in CSS 3 using the Flexible Box Layout Module .因此,为了完整起见,这里是使用灵活框布局模块以 CSS 3 为中心的最新方法。

So if you have simple markup like:因此,如果您有简单的标记,例如:

<div class="box">
  <div class="item1">A</div>
  <div class="item2">B</div>
  <div class="item3">C</div>
</div>

...and you want to center your items within the box, here's what you need on the parent element (.box): ...并且您想将您的项目集中在框中,这是您在父元素 (.box) 上需要的内容:

.box {
    display: flex;
    flex-wrap: wrap; /* Optional. only if you want the items to wrap */
    justify-content: center; /* For horizontal alignment */
    align-items: center; /* For vertical alignment */
}

 .box { display: flex; flex-wrap: wrap; /* Optional. only if you want the items to wrap */ justify-content: center; /* For horizontal alignment */ align-items: center; /* For vertical alignment */ } * { margin: 0; padding: 0; } html, body { height: 100%; } .box { height: 200px; display: flex; flex-wrap: wrap; justify-content: center; align-items: center; border: 2px solid tomato; } .box div { margin: 0 10px; width: 100px; } .item1 { height: 50px; background: pink; } .item2 { background: brown; height: 100px; } .item3 { height: 150px; background: orange; }
 <div class="box"> <div class="item1">A</div> <div class="item2">B</div> <div class="item3">C</div> </div>

If you need to support older browsers which use older syntax for flexbox here's a good place to look.如果您需要支持使用旧语法的旧浏览器,那么这里是一个不错的选择。

If you don't want to set a fixed width and don't want the extra margin, add display: inline-block to your element.如果您不想设置固定宽度并且不想要额外的边距,请将display: inline-block添加到您的元素。

You can use:您可以使用:

#element {
    display: table;
    margin: 0 auto;
}

Centering a div of unknown height and width将未知高度和宽度的 div 居中

Horizontally and vertically.水平和垂直。 It works with reasonably modern browsers (Firefox, Safari/WebKit, Chrome, Internet & Explorer & 10, Opera, etc.)它适用于相当现代的浏览器(Firefox、Safari/WebKit、Chrome、Internet & Explorer & 10、Opera 等)

 .content { position: absolute; left: 50%; top: 50%; transform: translate(-50%, -50%); }
 <div class="content">This works with any content</div>

Tinker with it further on Codepen or on JSBin .CodepenJSBin上进一步修改它。

Set the width and set margin-left and margin-right to auto .设置width并将margin-leftmargin-right设置为auto That's for horizontal only , though.不过,这仅适用于水平 If you want both ways, you'd just do it both ways.如果你想要两种方式,你就两种方式都做。 Don't be afraid to experiment;不要害怕尝试; it's not like you'll break anything.这不像你会破坏任何东西。

It cannot be centered if you don't give it a width.如果你不给它一个宽度,它就不能居中。 Otherwise, it will take, by default, the whole horizontal space.否则,默认情况下,它将占用整个水平空间。

CSS 3's box-align property CSS 3 的 box-align 属性

#outer {
    width: 100%;
    height: 100%;
    display: box;
    box-orient: horizontal;
    box-pack: center;
    box-align: center;
}

The way I usually do it is using absolute position:我通常这样做的方式是使用绝对位置:

#inner{
  left: 0;
  right: 0;
  margin-left: auto;
  margin-right: auto;
  position: absolute;
}

The outer div doesn't need any extra properties for this to work.外部 div 不需要任何额外的属性来工作。

I recently had to center a "hidden" div (ie, display:none; ) that had a tabled form within it that needed to be centered on the page.我最近不得不将一个“隐藏的” div (即display:none; )居中,其中有一个表格形式,需要在页面上居中。 I wrote the following jQuery code to display the hidden div and then update the CSS content to the automatic generated width of the table and change the margin to center it.我编写了以下 jQuery 代码来显示隐藏的 div,然后将 CSS 内容更新为自动生成的表格宽度并将边距更改为居中。 (The display toggle is triggered by clicking on a link, but this code wasn't necessary to display.) (显示切换是通过单击链接触发的,但此代码不是显示所必需的。)

NOTE: I'm sharing this code, because Google brought me to this Stack Overflow solution and everything would have worked except that hidden elements don't have any width and can't be resized/centered until after they are displayed.注意:我正在分享这段代码,因为谷歌把我带到了这个 Stack Overflow 解决方案,除了隐藏元素没有任何宽度并且在它们显示之前无法调整大小/居中之外,一切都会正常工作。

 $(function(){ $('#inner').show().width($('#innerTable').width()).css('margin','0 auto'); });
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="inner" style="display:none;"> <form action=""> <table id="innerTable"> <tr><td>Name:</td><td><input type="text"></td></tr> <tr><td>Email:</td><td><input type="text"></td></tr> <tr><td>Email:</td><td><input type="submit"></td></tr> </table> </form> </div>

For Firefox and Chrome:对于 Firefox 和 Chrome:

 <div style="width:100%;"> <div style="width: 50%; margin: 0px auto;">Text</div> </div>

For Internet Explorer, Firefox, and Chrome:对于 Internet Explorer、Firefox 和 Chrome:

 <div style="width:100%; text-align:center;"> <div style="width: 50%; margin: 0px auto; text-align:left;">Text</div> </div>

The text-align: property is optional for modern browsers, but it is necessary in Internet Explorer Quirks Mode for legacy browsers support. text-align:属性对于现代浏览器是可选的,但在 Internet Explorer Quirks Mode 中对于旧版浏览器支持是必需的。

Use:利用:

 #outerDiv { width: 500px; } #innerDiv { width: 200px; margin: 0 auto; }
 <div id="outerDiv"> <div id="innerDiv">Inner Content</div> </div>

Another solution for this without having to set a width for one of the elements is using the CSS 3 transform attribute.无需为其中一个元素设置宽度的另一种解决方案是使用 CSS 3 transform属性。

#outer {
  position: relative;
}

#inner {
  position: absolute;
  left: 50%;

  transform: translateX(-50%);
}

The trick is that translateX(-50%) sets the #inner element 50 percent to the left of its own width.诀窍是translateX(-50%)#inner元素设置在其自身宽度左侧的 50% 处。 You can use the same trick for vertical alignment.您可以使用相同的技巧进行垂直对齐。

Here's a Fiddle showing horizontal and vertical alignment.这是一个显示水平和垂直对齐的小提琴

More information is on Mozilla Developer Network .更多信息请参见 Mozilla 开发者网络

Chris Coyier who wrote an excellent post on 'Centering in the Unknown' on his blog. Chris Coyier 在他的博客上写了一篇关于“以未知为中心”的优秀文章 It's a roundup of multiple solutions.这是多种解决方案的综合。 I posted one that isn't posted in this question.我发布了一个未在此问题中发布的内容。 It has more browser support than the Flexbox solution, and you're not using display: table;它比Flexbox解决方案有更多的浏览器支持,而且你没有使用display: table; which could break other things.这可能会破坏其他东西。

/* This parent can be any width and height */
.outer {
  text-align: center;
}

/* The ghost, nudged to maintain perfect centering */
.outer:before {
  content: '.';
  display: inline-block;
  height: 100%;
  vertical-align: middle;
  width: 0;
  overflow: hidden;
}

/* The element to be centered, can
   also be of any width and height */
.inner {
  display: inline-block;
  vertical-align: middle;
  width: 300px;
}

I recently found an approach:我最近找到了一种方法:

#outer {
    position: absolute;
    left: 50%;
}

#inner {
    position: relative;
    left: -50%;
}

Both elements must be the same width to function correctly.两个元素必须具有相同的宽度才能正常工作。

For example, see this link and the snippet below:例如,请参阅此链接和下面的代码段:

 div#outer { height: 120px; background-color: red; } div#inner { width: 50%; height: 100%; background-color: green; margin: 0 auto; text-align: center; /* For text alignment to center horizontally. */ line-height: 120px; /* For text alignment to center vertically. */ }
 <div id="outer" style="width:100%;"> <div id="inner">Foo foo</div> </div>

If you have a lot of children under a parent, so your CSS content must be like this example on fiddle .如果您在父母下有很多孩子,那么您的 CSS 内容必须像fiddle 上的这个示例

The HTML content look likes this: HTML 内容如下所示:

<div id="outer" style="width:100%;">
    <div class="inner"> Foo Text </div>
    <div class="inner"> Foo Text </div>
    <div class="inner"> Foo Text </div>
    <div class="inner"> </div>
    <div class="inner"> </div>
    <div class="inner"> </div>
    <div class="inner"> </div>
    <div class="inner"> </div>
    <div class="inner"> Foo Text </div>
</div>

Then see this example on fiddle .然后在 fiddle 上查看这个示例

Centering only horizontally仅水平居中

In my experience, the best way to center a box horizontally is to apply the following properties:以我的经验,将盒子水平居中的最佳方法是应用以下属性:

The container:容器:

  • should have text-align: center;应该有text-align: center;

The content box:内容框:

  • should have display: inline-block;应该有display: inline-block;

Demo:演示:

 .container { width: 100%; height: 120px; background: #CCC; text-align: center; } .centered-content { display: inline-block; background: #FFF; padding: 20px; border: 1px solid #000; }
 <div class="container"> <div class="centered-content"> Center this! </div> </div>

See also this Fiddle !另见这个小提琴


Centering both horizontally & vertically水平和垂直居中

In my experience, the best way to center a box both vertically and horizontally is to use an additional container and apply the following properties:根据我的经验,将盒子垂直和水平居中的最佳方法使用额外的容器并应用以下属性:

The outer container:外容器:

  • should have display: table;应该有display: table;

The inner container:内部容器:

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

The content box:内容框:

  • should have display: inline-block;应该有display: inline-block;

Demo:演示:

 .outer-container { display: table; width: 100%; height: 120px; background: #CCC; } .inner-container { display: table-cell; vertical-align: middle; text-align: center; } .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"> Center this! </div> </div> </div>

See also this Fiddle !另见这个小提琴

Flexbox弹性盒

display: flex behaves like a block element and lays out its content according to the flexbox model. display: flex的行为类似于块元素,并根据 flexbox 模型布置其内容。 It works with justify-content: center .它适用于justify-content: center

Please note: Flexbox is compatible all browsers exept Internet Explorer.请注意: Flexbox 兼容除 Internet Explorer 之外的所有浏览器。 See display: flex not working on Internet Explorer for a complete and up to date list of browsers compatibility.有关浏览器兼容性的完整和最新列表,请参阅display: flex not working on Internet Explorer

 #inner { display: inline-block; } #outer { display: flex; justify-content: center; }
 <div id="outer"> <div id="inner">Foo foo</div> </div>


Text-align: center文本对齐:居中

Applying text-align: center the inline contents are centered within the line box.应用text-align: center内联内容在行框中居中。 However since the inner div has by default width: 100% you have to set a specific width or use one of the following:但是,由于内部 div 默认具有width: 100%您必须设置特定宽度或使用以下之一:

 #inner { display: inline-block; } #outer { text-align: center; }
 <div id="outer"> <div id="inner">Foo foo</div> </div>


Margin: 0 auto保证金:0自动

Using margin: 0 auto is another option and it is more suitable for older browsers compatibility.使用margin: 0 auto是另一种选择,它更适合旧浏览器的兼容性。 It works together with display: table .它与display: table一起使用。

 #inner { display: table; margin: 0 auto; }
 <div id="outer"> <div id="inner">Foo foo</div> </div>


Transform转换

transform: translate lets you modify the coordinate space of the CSS visual formatting model. transform: translate允许您修改 CSS 视觉格式化模型的坐标空间。 Using it, elements can be translated, rotated, scaled, and skewed.使用它,可以平移、旋转、缩放和倾斜元素。 To center horizontally it require position: absolute and left: 50% .要水平居中,它需要position: absoluteleft: 50%

 #inner { position: absolute; left: 50%; transform: translate(-50%, 0%); }
 <div id="outer"> <div id="inner">Foo foo</div> </div>


<center> (Deprecated) <center> (已弃用)

The tag <center> is the HTML alternative to text-align: center .标签<center>text-align: center的 HTML 替代品。 It works on older browsers and most of the new ones but it is not considered a good practice since this feature is obsolete and has been removed from the Web standards.它适用于旧浏览器和大多数新浏览器,但由于此功能已过时并且已从 Web 标准中删除,因此不被认为是一种好的做法。

 #inner { display: inline-block; }
 <div id="outer"> <center> <div id="inner">Foo foo</div> </center> </div>

This method also works just fine:此方法也可以正常工作:

div.container {
  display: flex;
  justify-content: center; /* For horizontal alignment */
  align-items: center;     /* For vertical alignment   */
}

For the inner <div> , the only condition is that its height and width must not be larger than the ones of its container.对于内部<div> ,唯一的条件是它的heightwidth不能大于其容器的高度和宽度。

The easiest way:最简单的方法:

 #outer { width: 100%; text-align: center; } #inner { margin: auto; width: 200px; }
 <div id="outer"> <div id="inner">Blabla</div> </div>

If width of the content is unknown you can use the following method .如果内容的宽度未知,您可以使用以下方法 Suppose we have these two elements:假设我们有这两个元素:

  • .outer -- full width .outer -- 全宽
  • .inner -- no width set (but a max-width could be specified) .inner -- 没有设置宽度(但可以指定最大宽度)

Suppose the computed width of the elements are 1000 pixels and 300 pixels respectively.假设计算出的元素宽度分别为 1000 像素和 300 像素。 Proceed as follows:进行如下操作:

  1. Wrap .inner inside .center-helper.inner包裹在.center-helper
  2. Make .center-helper an inline block;使.center-helper成为内联块; it becomes the same size as .inner making it 300 pixels wide.它变成与.inner相同的大小,使其宽 300 像素。
  3. Push .center-helper 50% right relative to its parent; .center-helper相对于其父级向右推 50%; this places its left at 500 pixels wrt.这将其左侧放置在 500 像素处。 outer.外。
  4. Push .inner 50% left relative to its parent; .inner相对于其父级向左推 50%; this places its left at -150 pixels wrt.这将其左侧放置在 -150 像素处。 center helper which means its left is at 500 - 150 = 350 pixels wrt.中心助手,这意味着它的左边是 500 - 150 = 350 像素 wrt。 outer.外。
  5. Set overflow on .outer to hidden to prevent horizontal scrollbar..outer上的溢出设置为隐藏以防止水平滚动条。

Demo:演示:

 body { font: medium sans-serif; } .outer { overflow: hidden; background-color: papayawhip; } .center-helper { display: inline-block; position: relative; left: 50%; background-color: burlywood; } .inner { display: inline-block; position: relative; left: -50%; background-color: wheat; }
 <div class="outer"> <div class="center-helper"> <div class="inner"> <h1>A div with no defined width</h1> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.<br> Duis condimentum sem non turpis consectetur blandit.<br> Donec dictum risus id orci ornare tempor.<br> Proin pharetra augue a lorem elementum molestie.<br> Nunc nec justo sit amet nisi tempor viverra sit amet a ipsum.</p> </div> </div> </div>

Flex have more than 97% browser support coverage and might be the best way to solve these kind of problems within few lines: Flex 拥有超过 97% 的浏览器支持覆盖率,并且可能是在几行内解决此类问题的最佳方法:

#outer {
  display: flex;
  justify-content: center;
}

You can do something like this你可以做这样的事情

#container {
   display: table;
   width: <width of your container>;
   height: <height of your container>;
}

#inner {
   width: <width of your center div>;
   display: table-cell;
   margin: 0 auto;
   text-align: center;
   vertical-align: middle;
}

This will also align the #inner vertically.这也将垂直对齐#inner If you don't want to, remove the display and vertical-align properties;如果您不想这样做,请删除displayvertical-align属性;

Here is what you want in the shortest way.这是你想要的最短的方式。

JSFIDDLE JSFIDDLE

#outer {
  margin - top: 100 px;
  height: 500 px; /* you can set whatever you want */
  border: 1 px solid# ccc;
}

#inner {
  border: 1 px solid# f00;
  position: relative;
  top: 50 % ;
  transform: translateY(-50 % );
}

You can use display: flex for your outer div and to horizontally center you have to add justify-content: center您可以使用display: flex作为您的外部 div 并水平居中您必须添加justify-content: center

#outer{
    display: flex;
    justify-content: center;
}

or you can visit w3schools - CSS flex Property for more ideas.或者您可以访问w3schools - CSS flex 属性以获得更多想法。

Well, I managed to find a solution that maybe will fit all situations, but uses JavaScript:好吧,我设法找到了一个可能适合所有情况的解决方案,但使用 JavaScript:

Here's the structure:这是结构:

<div class="container">
  <div class="content">Your content goes here!</div>
  <div class="content">Your content goes here!</div>
  <div class="content">Your content goes here!</div>
</div>

And here's the JavaScript snippet:这是 JavaScript 片段:

$(document).ready(function() {
  $('.container .content').each( function() {
    container = $(this).closest('.container');
    content = $(this);

    containerHeight = container.height();
    contentHeight = content.height();

    margin = (containerHeight - contentHeight) / 2;
    content.css('margin-top', margin);
  })
});

If you want to use it in a responsive approach, you can add the following:如果您想在响应式方法中使用它,可以添加以下内容:

$(window).resize(function() {
  $('.container .content').each( function() {
    container = $(this).closest('.container');
    content = $(this);

    containerHeight = container.height();
    contentHeight = content.height();

    margin = (containerHeight - contentHeight) / 2;
    content.css('margin-top', margin);
  })
});

One option existed that I found:我发现存在一个选项:

Everybody says to use:每个人都说使用:

margin: auto 0;

But there is another option.但还有另一种选择。 Set this property for the parent div.为父 div 设置此属性。 It works perfectly anytime:它随时都可以完美运行:

text-align: center;

And see, child go center.看,孩子去中心。

And finally CSS for you:最后为您提供 CSS:

#outer{
     text-align: center;
     display: block; /* Or inline-block - base on your need */
}

#inner
{
     position: relative;
     margin: 0 auto; /* It is good to be */
}

You can just simply use Flexbox like this:你可以像这样简单地使用Flexbox

 #outer { display: flex; justify-content: center }
 <div id="outer"> <div id="inner">Foo foo</div> </div>

Apply Autoprefixer for all browser support:为所有浏览器支持应用 Autoprefixer:

#outer {
    display: -webkit-box;
    display: -ms-flexbox;
    display: flex;
    width: 100%;
    -webkit-box-pack: center;
    -ms-flex-pack: center;
    justify-content: center
}

Or else要不然

Use transform :使用变换

 #inner { position: absolute; left: 50%; transform: translate(-50%) }
 <div id="outer"> <div id="inner">Foo foo</div> </div>

With Autoprefixer:使用自动前缀:

#inner {
    position: absolute;
    left: 50%;
    -webkit-transform: translate(-50%);
    -ms-transform:     translate(-50%);
    transform:         translate(-50%)
}

Try playing around with尝试玩弄

margin: 0 auto;

If you want to center your text too, try using:如果您也想将文本居中,请尝试使用:

text-align: center;

If anyone would like a jQuery solution for center align these divs:如果有人想要一个用于中心对齐这些 div 的 jQuery 解决方案:

$(window).bind("load", function() {
    var wwidth = $("#outer").width();
    var width = $('#inner').width();
    $('#inner').attr("style", "padding-left: " + wwidth / 2 + "px; margin-left: -" + width / 2 + "px;");
});

We can use Flexbox to achieve this really easily:我们可以使用Flexbox轻松实现这一点:

<div id="outer">
    <div id="inner">Foo foo</div>
</div>

Center a div inside a div horizontally :将 div水平居中在 div 内:

#outer {
   display: flex;
   justify-content: center;
}

在此处输入图像描述

Center a div inside a div vertically :将 div垂直居中在 div 内:

#outer {
    display: flex;
    align-items: center;
}

在此处输入图像描述

And, to completely middle the div vertically and horizontally:并且,要在垂直和水平方向上完全居中 div:

#outer{
    display: flex;
    justify-content: center;
    align-items: center;
}

在此处输入图像描述

Just add this CSS content into your CSS file.只需将此 CSS 内容添加到您的 CSS 文件中。 It will automatically center the content.它会自动将内容居中。

Align horizontally to center in CSS:在 CSS 中水平居中对齐:

#outer {
    display: flex;
    justify-content: center;
}

Align-vertically + horizontal to center in CSS:在 CSS 中垂直对齐 + 水平居中:

#outer {
    display: flex;
    justify-content: center;
    align-items: center;
}

A very simple and cross-browser answer to horizontal center is to apply this rule to the parent element:水平居中的一个非常简单且跨浏览器的答案是将此规则应用于父元素:

.parentBox {
    display: flex;
    justify-content: center
}

I have applied the inline style to the inner div.我已将内联样式应用于内部 div。 Use this one:使用这个:

<div id="outer" style="width:100%">  
    <div id="inner" style="display:table;margin:0 auto;">Foo foo</div>
</div>

With Grid带网格

A pretty simple and modern way is to use display: grid :一个非常简单和现代的方法是使用display: grid

 div { border: 1px dotted grey; } #outer { display: grid; place-items: center; height: 50px; /* not necessary */ }
 <!DOCTYPE html> <html> <head> </head> <body> <div id="outer"> <div>Foo foo</div> </div> </body> </html>

A nice thing I recently found, mixing the use of line-height + vertical-align and the 50% left trick, you can center a dynamically sized box inside another dynamically sized box, on both the horizontal and vertical using pure CSS.我最近发现的一件好事,混合使用line-height + vertical-align50% left 技巧,您可以使用纯 CSS 在水平和垂直方向将一个动态大小的框center在另一个动态大小的框内。

Note you must use spans (and inline-block ), tested in modern browsers + Internet Explorer 8. HTML:请注意,您必须使用在现代浏览器 + Internet Explorer 8 中测试过的 spans (和inline-block )。 HTML:

<h1>Center dynamic box using only css test</h1>
<div class="container">
  <div class="center">
    <div class="center-container">
      <span class="dyn-box">
        <div class="dyn-head">This is a head</div>
        <div class="dyn-body">
          This is a body<br />
          Content<br />
          Content<br />
          Content<br />
          Content<br />
        </div>
      </span>
    </div>
  </div>
</div>

CSS: CSS:

.container {
  position: absolute;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  overflow: hidden;
}

.center {
  position: absolute;
  left: 50%;
  top: 50%;
}

.center-container {
  position: absolute;
  left: -2500px;
  top: -2500px;
  width: 5000px;
  height: 5000px;
  line-height: 5000px;
  text-align: center;
  overflow: hidden;
}

.dyn-box {
  display: inline-block;
  vertical-align: middle;
  line-height: 100%;
  /* Purely asthetic below this point */
  background: #808080;
  padding: 13px;
  border-radius: 11px;
  font-family: arial;
}

.dyn-head {
  background: red;
  color: white;
  min-width: 300px;
  padding: 20px;
  font-size: 23px;
}

.dyn-body {
  padding: 10px;
  background: white;
  color: red;
}

See example here .请参见此处的示例

Use the below CSS content for #inner div:#inner div 使用以下 CSS 内容:

#inner {
  width: 50%;
  margin-left: 25%;
}

I mostly use this CSS content to center div s.我主要使用这个 CSS 内容来居中div

It's possible using CSS 3 Flexbox .可以使用CSS 3 Flexbox You have two methods when using Flexbox.使用 Flexbox 时有两种方法。

  1. Set the parent display:flex;设置父display:flex; and add properties {justify-content:center; ,align-items:center;}并添加属性{justify-content:center; ,align-items:center;} {justify-content:center; ,align-items:center;} to your parent element. {justify-content:center; ,align-items:center;}到你的父元素。

 #outer { display: flex; justify-content: center; align-items: center; }
 <div id="outer" style="width:100%"> <div id="inner">Foo foo</div> </div>

  1. Set the parent display:flex and add margin:auto;设置父display:flex并添加margin:auto; to the child.给孩子。

 #outer { display: flex; } #inner { margin: auto; }
 <div id="outer" style="width:100%"> <div id="inner">Foo foo</div> </div>

CSS 3: CSS 3:

You can use the following style on the parent container to distribute child elements evenly horizontally:您可以在父容器上使用以下样式将子元素水平均匀分布:

display: flex;
justify-content: space-between;  // <-- space-between or space-around

A nice DEMO regarding the different values for justify-content .关于justify-content不同值的一个很好的演示

在此处输入图像描述

CanIUse: Browser-Compatability CanIUse:浏览器兼容性

Try it!:试试看!:

 #containerdiv { display: flex; justify-content: space-between; } #containerdiv > div { background-color: blue; width: 50px; color: white; text-align: center; }
 <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>JS Bin</title> </head> <body> <div id="containerdiv"> <div>88</div> <div>77</div> <div>55</div> <div>33</div> <div>40</div> <div>45</div> </div> </body> </html>

#inner {
    width: 50%;
    margin: 0 auto;
}

You can attain this using the CSS Flexbox .您可以使用CSS Flexbox来实现这一点。 You just need to apply 3 properties to the parent element to get everything working.您只需将 3 个属性应用于父元素即可让一切正常工作。

#outer {
  display: flex;
  align-content: center;
  justify-content: center;
}

Have a look at the code below this will make you understand the properties much better.看看下面的代码,这将使您更好地理解这些属性。

Get to know more aboutCSS Flexbox进一步了解CSS Flexbox

 #outer { display: flex; align-items: center; justify-content: center; border: 1px solid #ddd; width: 100%; height: 200px; }
 <div id="outer"> <div id="inner">Foo foo</div> </div>

How can I horizontally center a <div> within another <div> using CSS?如何使用 CSS 在另一个<div>中水平居中<div>

Here's a non-exhaustive list of centering approaches, using:以下是居中方法的非详尽列表,使用:

  • margin and auto marginauto
  • margin and calc() margincalc()
  • padding and box-sizing and calc() paddingbox-sizingcalc()
  • position: absolute and negative margin-left position: absolutemargin-left
  • position: absolute and negative transform: translateX() position: absolutetransform: translateX()
  • display: inline-block and text-align: center display: inline-blocktext-align: center
  • display: table and display: table-cell display: tabledisplay: table-cell
  • display: flex and justify-content: center display: flexjustify-content: center
  • display: grid and justify-items: center display: gridjustify-items: center

1. Center a block-level element using auto for horizontal margins 1. 使用auto为水平边距居中一个块级元素

 .outer { width: 300px; height: 180px; background-color: rgb(255, 0, 0); } .inner { width: 150px; height: 180px; margin: 0 auto; background-color: rgb(255, 255, 0); }
 <div class="outer"> <div class="inner"></div> </div>

2. Center a block-level element using calc with horizontal margins 2. 使用带有水平边距的calc将块级元素居中

 .outer { width: 300px; height: 180px; background-color: rgb(255, 0, 0); } .inner { width: 150px; height: 180px; margin: 0 calc((300px - 150px) / 2); background-color: rgb(255, 255, 0); }
 <div class="outer"> <div class="inner"></div> </div>

3. Center a block-level element using calc with horizontal padding + box-sizing 3. 使用calc和水平填充 + box-sizing使块级元素居中

 .outer { width: 300px; height: 180px; padding: 0 calc((300px - 150px) / 2); background-color: rgb(255, 0, 0); box-sizing: border-box; } .inner { width: 150px; height: 180px; background-color: rgb(255, 255, 0); }
 <div class="outer"> <div class="inner"></div> </div>

4. Center a block-level element using position: absolute with left: 50% and negative margin-left 4. 使用position: absolute with left: 50%margin-left将块级元素居中

 .outer { position: relative; width: 300px; height: 180px; background-color: rgb(255, 0, 0); } .inner { position: absolute; left: 50%; width: 150px; height: 180px; margin-left: -75px; background-color: rgb(255, 255, 0); }
 <div class="outer"> <div class="inner"></div> </div>

5. Center a block-level element using position: absolute with left: 50% and negative transform: translateX() 5. 使用position: absolute with left: 50%transform: translateX()将块级元素居中

 .outer { position: relative; width: 300px; height: 180px; background-color: rgb(255, 0, 0); } .inner { position: absolute; left: 50%; width: 150px; height: 180px; background-color: rgb(255, 255, 0); transform: translateX(-75px); }
 <div class="outer"> <div class="inner"></div> </div>

6. Center an element using display: inline-block and text-align: center 6. 使用display: inline-blocktext-align: center元素居中

 .outer { position: relative; width: 300px; height: 180px; text-align: center; background-color: rgb(255, 0, 0); } .inner { display: inline-block; width: 150px; height: 180px; background-color: rgb(255, 255, 0); }
 <div class="outer"> <div class="inner"></div> </div>

7. Center an element using display: table , padding and box-sizing 7. 使用display: table , paddingbox-sizing使元素居中

 .outer { display: table; width: 300px; height: 180px; padding: 0 75px; background-color: rgb(255, 0, 0); box-sizing: border-box; } .inner { display: table-cell; background-color: rgb(255, 255, 0); }
 <div class="outer"> <div class="inner"></div> </div>

8. Center an element using display: flex and justify-content: center 8. 使用display: flexjustify-content: center将元素居中

 .outer { display: flex; justify-content: center; width: 300px; height: 180px; background-color: rgb(255, 0, 0); } .inner { flex: 0 0 150px; background-color: rgb(255, 255, 0); }
 <div class="outer"> <div class="inner"></div> </div>

9. Center an element using display: grid and justify-items: center 9. 使用display: gridjustify-items: center将元素居中

 .outer { display: grid; justify-items: center; width: 300px; height: 180px; background-color: rgb(255, 0, 0); } .inner { width: 150px; background-color: rgb(255, 255, 0); }
 <div class="outer"> <div class="inner"></div> </div>

This is the best example to horizontally center a <div>这是水平居中 <div> 的最佳示例

 #outer { display: flex; align-items: center; justify-content: center; }
 <!DOCTYPE html> <html> <head> </head> <body> <div id="outer"> <div id="inner">Foo foo</div> </div> </body> </html>

Make it simple!让它变得简单!

 #outer { display: flex; justify-content: center; }
 <div id="outer"> <div id="inner">Foo foo</div> </div>

Center an Element Without Need of a Wrapper/Parent with Dynamic Height & Width使元素居中而不需要具有动态高度和宽度的包装器/父级

No side effect: It will not limit a centered element's width less than the viewport width, when using margins in Flexbox inside a centered element无副作用:在居中元素内使用 Flexbox 中的边距时,它不会限制居中元素的宽度小于视口宽度

position: fixed;
top: 0; left: 0;
transform: translate(calc(50vw - 50%));

Horizontally + vertically center, if its height is same as the width:水平+垂直居中,如果其高度与宽度相同:

position: fixed;
top: 0; left: 0;
transform: translate(calc(50vw - 50%), calc(50vh - 50%));

To centre an element horizontally you can use these methods:要使元素水平居中,您可以使用以下方法:

Method 1: Using margin property方法一:使用边距属性

If the element is a block-level element then you can centre the element by using margin property.如果元素是块级元素,则可以使用 margin 属性使元素居中。 Set margin-left and margin-right is to auto (Shorthand - margin: 0 auto ).margin-leftmargin-right设置为 auto (简写 - margin: 0 auto )。

This will align the element to the centre horizontally.这会将元素水平对齐到中心。 If the element is not a block-level element then add display: block property to it.如果元素不是块级元素,则向其添加display: block属性。

 #outer { background-color: silver; } #inner { width: max-content; margin: 0 auto; background-color: #f07878; }
 <div id="outer"> <div id="inner">Foo foo</div> </div>

Method 2: Using CSS flexbox方法二:使用 CSS flexbox

Create a flexbox container and use justify-content property and set it to center .创建一个 flexbox 容器并使用justify-content属性并将其设置为center This will align all elements horizontally to the centre of the webpage.这会将所有元素水平对齐到网页的中心。

 #outer { display: flex; justify-content: center; background-color: silver; } #inner { background-color: #f07878; }
 <div id="outer"> <div id="inner">Foo foo</div> </div>

Method 3: Using position absolute technique方法3:使用绝对位置技术

This is a classic method to centre the element.这是使元素居中的经典方法。 Set postion:relative to the outer element.设置postion:relative对于外部元素。 Set the inner element's position to absolute and left: 50% .将内部元素的位置设置为 absolute 和left: 50% This will push the inner element to start from the centre of the outer element.这将推动内部元素从外部元素的中心开始。 Now use the transform property and set transform: translateX(-50%) this will make the element centre horizontally.现在使用 transform 属性并设置transform: translateX(-50%)这将使元素水平居中。

 #outer { position: relative; background-color: silver; } #inner { position: absolute; left: 50%; transform: translateX(-50%); background-color: #f07878; }
 <div id="outer"> <center> <div id="inner">Foo foo</div> </center> </div>

One of the easiest ways...最简单的方法之一...

<!DOCTYPE html>
<html>
    <head>
        <style>
            #outer-div {
                width: 100%;
                text-align: center;
                background-color: #000
            }
            #inner-div {
                display: inline-block;
                margin: 0 auto;
                padding: 3px;
                background-color: #888
            }
        </style>
    </head>

    <body>
       <div id ="outer-div" width="100%">
           <div id ="inner-div"> I am a easy horizontally centered div.</div>
       <div>
    </body>
</html>

If you have a parent of some height say, body{height: 200px} or like the below has parent div#outer with height 200px, then add CSS content as below如果你有一个身高的父母说, body{height: 200px}或像下面这样有高度为 200px 的父 div#outer,然后添加 CSS 内容如下

HTML: HTML:

<div id="outer">
  <div id="centered">Foo foo</div>
</div>

CSS: CSS:

#outer{
  display: flex;
  width: 100%;
  height: 200px;
}
#centered {
  margin: auto;
}

Then child content, say div#centered content, will be vertically or horizontally middle, without using any position CSS.然后子内容,比如 div#centered 内容,将垂直或水平居中,而不使用任何位置 CSS。 To remove vertically middle behavior then just modify to below CSS code:要删除垂直中间行为,只需修改以下 CSS 代码:

#centered {
  margin: 0px auto;
}

or或者

#outer{
  display: flex;
  width: 100%;
  height: 200px;
}
#centered {
  margin: auto;
}

<div id="outer">
  <div id="centered">Foo foo</div>
</div>

Demo: https://jsfiddle.net/jinny/p3x5jb81/5/演示: https ://jsfiddle.net/jinny/p3x5jb81/5/

To add only a border to show the inner div is not 100% by default:仅添加边框以显示内部 div 默认情况下不是 100%:

 #outer{ display: flex; width: 100%; height: 200px; border: 1px solid #000000; } #centered { margin: auto; border: 1px solid #000000; }
 <div id="outer"> <div id="centered">Foo foo</div> </div>

DEMO: http://jsfiddle.net/jinny/p3x5jb81/9演示:http: //jsfiddle.net/jinny/p3x5jb81/9

With Sass (SCSS syntax) you can do this with a mixin :使用Sass (SCSS 语法),您可以使用mixin执行此操作:

With translate翻译

// Center horizontal mixin
@mixin center-horizontally {
  position: absolute;
  left: 50%;
  transform: translate(-50%, -50%);
}

// Center horizontal class
.center-horizontally {
    @include center-horizontally;
}

In an HTML tag:在 HTML 标记中:

<div class="center-horizontally">
    I'm centered!
</div>

Remember to add position: relative;记得添加position: relative; to the parent HTML element.到父 HTML 元素。


With Flexbox使用弹性盒

Using flex , you can do this:使用flex ,您可以这样做:

@mixin center-horizontally {
  display: flex;
  justify-content: center;
}

// Center horizontal class
.center-horizontally {
    @include center-horizontally;
}

In an HTML tag:在 HTML 标记中:

<div class="center-horizontally">
    <div>I'm centered!</div>
</div>

Try this CodePen !试试这个 CodePen

To align a div within a div in middle -要在中间的 div 中对齐 div -

 .outer{ width: 300px; /* For example */ height: 300px; /* For example */ background: red; } .inner{ position: relative; top: 50%; left: 50%; transform: translate(-50%, -50%); width: 200px; height: 200px; background: yellow; }
 <body> <div class='outer'> <div class='inner'></div> </div> </body>

This will align the internal div in the middle, both vertically and horizontally.这将在中间垂直和水平对齐内部 div。

Just do this:只需这样做:

<div id="outer">
  <div id="inner">Foo foo</div>
</div>

CSS CSS

#outer{
  display: grid;
  place-items: center;
}

This can be done by using lots of methods.这可以通过使用很多方法来完成。 Many guys'/gals' given answers are correct and working properly.许多男人/女孩给出的答案是正确的并且工作正常。 I'll give one more different pattern.我再给出一种不同的模式。

In the HTML fileHTML文件中

<div id="outer">
  <div id="inner">Foo foo</div>
</div>

In the CSS fileCSS文件中

#outer{
  width: 100%;
}

#inner{
  margin: auto;
}

I just use the simplest solution, but it works in all browsers:我只是使用最简单的解决方案,但它适用于所有浏览器:

<!doctype html>
<html>
    <head>
        <meta charset="utf-8">
        <title>center a div within a div?</title>
        <style type="text/css">
            *{
                margin: 0;
                padding: 0;
            }

            #outer{
                width: 80%;
                height: 500px;
                background-color: #003;
                margin: 0 auto;
            }

            #outer p{
                color: #FFF;
                text-align: center;
            }

            #inner{
                background-color: #901;
                width: 50%;
                height: 100px;
                margin: 0 auto;

            }

            #inner p{
                color: #FFF;
                text-align: center;
            }
        </style>
    </head>

    <body>
        <div id="outer"><p>this is the outer div</p>
            <div id="inner">
                <p>this is the inner div</p>
            </div>
        </div>
    </body>
</html>

Try out this below CSS code:试试下面的 CSS 代码:

<style>
    #outer {
        display: inline-block;
        width: 100%;
        height: 100%;
        text-align: center;
        vertical-align: middle;
    }

    #outer > #inner {
        display: inline-block;
        font-size: 19px;
        margin: 20px;
        max-width: 320px;
        min-height: 20px;
        min-width: 30px;
        padding: 14px;
        vertical-align: middle;
    }
</style>

Apply above CSS via below HTML code, to center horizontally and to center vertically (aka: align vertically in middle) :通过下面的 HTML 代码应用上面的 CSS,水平居中和垂直居中(又名:在中间垂直对齐)

<div id="outer">
    <div id="inner">
    ...These <div>ITEMS</div> <img src="URL"/> are in center...
    </div>
</div>

After applying CSS & using above HTML, that section in webpage would look like this:应用 CSS 并使用上述 HTML 后,网页中的该部分将如下所示:

BEFORE applying code:
┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
┃V..Middle & H..Center        ┣━1
┃                             ┣━2
┃                             ┣━3
┗┳━━━━━━┳━━━━━━┳━━━━━━┳━━━━━━┳┛
 1      2      3      4      5

AFTER:
┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
┃                             ┣━1
┃    V..Middle & H..Center    ┣━2
┃                             ┣━3
┗┳━━━━━━┳━━━━━━┳━━━━━━┳━━━━━━┳┛
 1      2      3      4      5

To center "inner" elements horizontally inside the "outer" wrapper, the "inner" elements (of type DIV, IMG, etc) need to have "inline" CSS properties, such as these: display:inline or display:inline-block, etc, THEN "outer" CSS property text-align:center can work on "inner" elements. 要在“外部”包装器中水平居中“内部”元素,“内部”元素(DIV、IMG 等类型)需要具有“内联”CSS 属性,例如:display:inline 或 display:inline-block等,然后“外部”CSS 属性 text-align:center 可以在“内部”元素上工作。

So near to minimum CSS code are these:如此接近最少的 CSS 代码是:

<div id="outer">
    <img class="inner2" src="URL-1"> <img class="inner2" src="URL-2">
</div>

Apply above CSS via below HTML code, to center (horizontally) :通过下面的 HTML 代码将上面的 CSS 应用到中心(水平)

BEFORE applying code:
┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
┃┍━━━━━━━━━━┑                     ┃
┃│ img URL1 │                     ┃
┃┕━━━━━━━━━━┙                     ┃
┃┍━━━━━━━━━━┑                     ┃
┃│ img URL2 │                     ┃
┃┕━━━━━━━━━━┙                     ┃
┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛

AFTER:
┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
┃    ┍━━━━━━━━━━┑ ┍━━━━━━━━━━┑    ┣━1
┃    │ img URL1 │ │ img URL2 │    ┣━2
┃    ┕━━━━━━━━━━┙ ┕━━━━━━━━━━┙    ┣━3
┗┳━━━━━━━┳━━━━━━━┳━━━━━━━┳━━━━━━━┳┛
 1       2       3       4       5

After applying CSS & using above HTML, that line in webpage would look like this:应用 CSS 并使用上述 HTML 后,网页中的该行将如下所示:

<style>
    #outer {
        width: 100%;
        text-align: center;
    }

    #outer > img, #outer > div {
        display: inline-block;
    }
</style>

If you want to avoid specifying class="inner2" attribute everytime for each "inner" elements, then use such CSS in early: 如果您想避免每次为每个“内部”元素指定 class="inner2" 属性,请尽早使用此类 CSS:
BEFORE applying code:
┏━━━━━━━━━━━━━━━━━━━━━━━━━━┓
┃┍━━━━━━━━┑                ┃
┃│img URL1│                ┃
┃┕━━━━━━━━┙                ┃
┃Text1                     ┃
┃┍━━━━━━━━┑                ┃
┃│img URL2│                ┃
┃┕━━━━━━━━┙                ┃
┃Text2                     ┃
┗━━━━━━━━━━━━━━━━━━━━━━━━━━┛

AFTER:
┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
┃   ┍━━━━━━━━━┑     ┍━━━━━━━━┑        ┣━1
┃   │img URL1 │     │img URL2│        ┣━2
┃   ┕━━━━━━━━━┙Text1┕━━━━━━━━┙Text2   ┣━3
┗┳━━━━━━━━┳━━━━━━━━┳━━━━━━━━┳━━━━━━━━┳┛
 1        2        3        4        5

So above CSS can be applied like below, to center items (horizontally) inside the "outer" wrapper:所以上面的 CSS 可以像下面这样应用,在“外部”包装器内(水平)居中:

 <div id="outer"> <img src="URL-1"> Text1 <img src="URL-2"> Text2 </div>

After applying CSS & using above HTML, that line in webpage would look like this:应用 CSS 并使用上述 HTML 后,网页中的该行将如下所示:

<style>
    .outer2 {
        width: 100%;
        text-align: center;
    }

    .outer2 > div, .outer2 > div > img {
        display: inline-block;
    }
</style>

The "id" attribute's unique name/value should be used only once for only one HTML element in one webpage, So CSS properties of same "id" name cannot be repeatedly used on multiple HTML elements, (some web-browser incorrectly allows to use same id on multiple elements). “id”属性的唯一名称/值只能用于一个网页中的一个 HTML 元素,因此同一“id”名称的 CSS 属性不能在多个 HTML 元素上重复使用,(某些网络浏览器错误地允许使用多个元素上的相同 ID)。
So when you need many lines in same webpage, that need to show internal elements/items in center (horizontally) in that line, then you may use such CSS "class" (aka: CSS group, CSS repeater) : 因此,当您在同一网页中需要多行时,需要在该行的中心(水平)显示内部元素/项目,那么您可以使用这样的 CSS“类”(又名:CSS 组、CSS 中继器)
<style>
    .outer2 {
        width: 100%;
        text-align: center;
        vertical-align: middle;
    }

    .outer2 > div, .outer2 > div > img {
        display: inline-block;
        vertical-align: middle;
    }
</style>

So above CSS can be applied like below, to center items (horizontally) inside the "outer2" wrapper:所以上面的 CSS 可以像下面这样应用,在“outer2”包装器中居中(水平地)项目:

<div class="outer2">
    <div>
        Line1: <img src="URL-1"> Text1 <img src="URL-2">
    </div>
</div>
...
<div class="outer2">
    <div>
        Line2: <img src="URL-3"> Text2 <img src="URL-4">
    </div>
</div>

After applying CSS & using above HTML, those lines in webpage would look like this:应用 CSS 并使用上述 HTML 后,网页中的这些行将如下所示:

BEFORE applying code:
┏━━━━━━━━━━━━━━━━━━━━━━┓
┃Line1:                ┃
┃┍━━━━━━━━┑            ┃
┃│img URL1│            ┃
┃┕━━━━━━━━┙            ┃
┃Text1                 ┃
┃┍━━━━━━━━┑            ┃
┃│img URL2│            ┃
┃┕━━━━━━━━┙            ┃
┗━━━━━━━━━━━━━━━━━━━━━━┛
........................
┏━━━━━━━━━━━━━━━━━━━━━━┓
┃Line2:                ┃
┃┍━━━━━━━━┑            ┃
┃│img URL3│            ┃
┃┕━━━━━━━━┙            ┃
┃Text2                 ┃
┃┍━━━━━━━━┑            ┃
┃│img URL4│            ┃
┃┕━━━━━━━━┙            ┃
┗━━━━━━━━━━━━━━━━━━━━━━┛

AFTER:
┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
┃         ┍━━━━━━━━┑     ┍━━━━━━━━┑   ┣━1
┃   Line1:│img URL1│Text1│img URL2│   ┣━2
┃         ┕━━━━━━━━┙     ┕━━━━━━━━┙   ┣━3
┗┳━━━━━━━━┳━━━━━━━━┳━━━━━━━━┳━━━━━━━━┳┛
 1        2        3        4        5
.......................................
┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
┃         ┍━━━━━━━━┑     ┍━━━━━━━━┑   ┣━1
┃   Line2:│img URL3│Text2│img URL4│   ┣━2
┃         ┕━━━━━━━━┙     ┕━━━━━━━━┙   ┣━3
┗┳━━━━━━━━┳━━━━━━━━┳━━━━━━━━┳━━━━━━━━┳┛
 1        2        3        4        5

To vertically align in middle, we would need to use below CSS code : 要在中间垂直对齐,我们需要使用下面的 CSS 代码
 <style> .outer2 { width: 100%; text-align: center; vertical-align: middle; } .outer2 > div, .outer2 > div > img { display: inline-block; vertical-align: middle; } </style>

So above CSS can be applied like below, to center items horizontally and to vertically align in middle of the "outer2" wrapper:所以上面的 CSS 可以像下面这样应用,将项目水平居中并在“outer2”包装器的中间垂直对齐:

 <div class="outer2"> <div> Line1: <img src="URL-1"> Text1 <img src="URL-2"> </div> </div> ... <div class="outer2"> <div> Line2: <img src="URL-3"> Text2 <img src="URL-4"> </div> </div>

After applying CSS & using above HTML, those lines in webpage would look like this:应用 CSS 并使用上述 HTML 后,网页中的这些行将如下所示:

 BEFORE applying code: ┏━━━━━━━━━━━━━━━━━━━━━━┓ ┃Line1: ┃ ┃┍━━━━━━━━┑ ┃ ┃│img URL1│ ┃ ┃┕━━━━━━━━┙ ┃ ┃Text1 ┃ ┃┍━━━━━━━━┑ ┃ ┃│img URL2│ ┃ ┃┕━━━━━━━━┙ ┃ ┗━━━━━━━━━━━━━━━━━━━━━━┛ ........................ ┏━━━━━━━━━━━━━━━━━━━━━━┓ ┃Line2: ┃ ┃┍━━━━━━━━┑ ┃ ┃│img URL3│ ┃ ┃┕━━━━━━━━┙ ┃ ┃Text2 ┃ ┃┍━━━━━━━━┑ ┃ ┃│img URL4│ ┃ ┃┕━━━━━━━━┙ ┃ ┗━━━━━━━━━━━━━━━━━━━━━━┛ AFTER: ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ ┃ ┍━━━━━━━━┑ ┍━━━━━━━━┑ ┣━1 ┃ Line1:│img URL1│Text1│img URL2│ ┣━2 ┃ ┕━━━━━━━━┙ ┕━━━━━━━━┙ ┣━3 ┗┳━━━━━━━━┳━━━━━━━━┳━━━━━━━━┳━━━━━━━━┳┛ 1 2 3 4 5 ....................................... ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ ┃ ┍━━━━━━━━┑ ┍━━━━━━━━┑ ┣━1 ┃ Line2:│img URL3│Text2│img URL4│ ┣━2 ┃ ┕━━━━━━━━┙ ┕━━━━━━━━┙ ┣━3 ┗┳━━━━━━━━┳━━━━━━━━┳━━━━━━━━┳━━━━━━━━┳┛ 1 2 3 4 5

You can use CSS Flexbox .您可以使用CSS Flexbox

#inner {
    display: flex;
    justify-content: center;
}

You can learn more about it on this link: https://css-tricks.com/snippets/css/a-guide-to-flexbox/您可以在此链接上了解更多信息: https ://css-tricks.com/snippets/css/a-guide-to-flexbox/

The easiest answer: Add margin:auto;最简单的答案:添加边距:自动; to inner.向内。

<div class="outer">
  <div class="inner">
    Foo foo
  </div>
</div>

CSS code CSS 代码

.outer{
    width: 100%;
    height: 300px;
    background: yellow;
}

.inner{
    width: 30%;
    height: 200px;
    margin: auto;
    background: red;
    text-align: center
}

Check my CodePen link: http://codepen.io/feizel/pen/QdJJrK检查我的CodePen链接: http ://codepen.io/feizel/pen/QdJJrK

在此处输入图像描述

It can also be centered horizontally and vertically using absolute positioning, like this:它也可以使用绝对定位水平和垂直居中,如下所示:

#outer{
    position: relative;
}

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

The best known way which is used widely and work in many browsers including the old ones, is using margin as below:在包括旧浏览器在内的许多浏览器中广泛使用并工作的最著名的方法是使用如下margin

 #parent { width: 100%; background-color: #CCCCCC; } #child { width: 30%; /* We need the width */ margin: 0 auto; /* This does the magic */ color: #FFFFFF; background-color: #000000; padding: 10px; text-align: center; }
 <div id="parent"> <div id="child">I'm the child and I'm horizontally centered! My daddy is a greyish div dude!</div> </div>

Run the code to see how it works.运行代码,看看它是如何工作的。 Also, there are two important things you shouldn't forget in your CSS when you try to center this way: margin: 0 auto;此外,当您尝试以这种方式居中时,您不应该在 CSS 中忘记两件重要的事情: margin: 0 auto; . . That makes it the div center as wanted.这使它成为所需的 div 中心。 Plus don't forget width of the child, otherwise it won't get centered as expected!另外不要忘记孩子的width ,否则它不会像预期的那样居中!

Center a div in a div在 div 中居中 div

 .outer { display: -webkit-flex; display: flex; //-webkit-justify-content: center; //justify-content: center; //align-items: center; width: 100%; height: 100px; background-color: lightgrey; } .inner { background-color: cornflowerblue; padding: 2rem; margin: auto; //align-self: center; }
 <div class="outer"> <div class="inner">Foo foo</div> </div>

Use:利用:

<div id="parent">
  <div class="child"></div>
</div>

Style:风格:

#parent {
   display: flex;
   justify-content: center;
}

If you want to center it horizontally you should write as below:如果你想水平居中,你应该写如下:

#parent {
   display: flex;
   justify-content: center;
   align-items: center;
}

You can use the calc method.您可以使用 calc 方法。 The usage is for the div you're centering.用法适用于您要居中的 div。 If you know its width, let's say it's 1200 pixels, go for:如果您知道它的宽度,假设它是 1200 像素,请选择:

.container {
    width:1200px;
    margin-left: calc(50% - 600px);
}

So basically it'll add a left margin of 50% minus half the known width.所以基本上它会增加 50% 的左边距减去已知宽度的一半。

Here is another way to center horizontally using Flexbox and without specifying any width to the inner container.这是另一种使用Flexbox水平居中的方法,无需为内部容器指定任何宽度。 The idea is to use pseudo elements that will push the inner content from the right and the left.这个想法是使用伪元素从左右推动内部内容。

Using flex:1 on pseudo element will make them fill the remaining spaces and take equal size and the inner container will get centered.在伪元素上使用flex:1将使它们填充剩余的空间并采用相同的大小,并且内部容器将居中。

 .container { display: flex; border: 1px solid; } .container:before, .container:after { content: ""; flex: 1; } .inner { border: 1px solid red; padding: 5px; }
 <div class="container"> <div class="inner"> Foo content </div> </div>

We can also consider the same situation for vertical alignment by simply changing the direction of flex to column:我们也可以通过简单地将 flex 的方向更改为 column 来考虑垂直对齐的相同情况:

 .container { display: flex; flex-direction: column; border: 1px solid; min-height: 200px; } .container:before, .container:after { content: ""; flex: 1; } .inner { border: 1px solid red; padding: 5px; }
 <div class="container"> <div class="inner"> Foo content </div> </div>

The best I have used in my various projects is我在各种项目中使用过的最好的是

<div class="outer">
    <div class="inner"></div>
</div>
.outer{
  width: 500px;
  height: 500px;
  position: relative;
  background: yellow;
}
.inner{
  width: 100px;
  height: 100px;
  background:red;
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
}

fiddle link小提琴链接

This will surely center your #inner both horizontally and vertically.这肯定会让你的#inner水平和垂直居中。 This is also compatible in all browsers.这在所有浏览器中也兼容。 I just added extra styling just to show how it is centered.我只是添加了额外的样式来显示它是如何居中的。

 #outer { background: black; position: relative; width:150px; height:150px; } #inner { background:white; position: absolute; left:50%; top: 50%; transform: translate(-50%,-50%); -webkit-transform: translate(-50%,-50%); -moz-transform: translate(-50%,-50%); -o-transform: translate(-50%,-50%); }
 <div id="outer"> <div id="inner">Foo foo</div> </div>

But of course if you only want it horizontally aligned, This may help you.但是当然,如​​果您只希望它水平对齐,这可能会对您有所帮助。

 #outer { background: black; position: relative; width:150px; height:150px; } #inner { background:white; position: absolute; left:50%; transform: translate(-50%,0); -webkit-transform: translate(-50%,0); -moz-transform: translate(-50%,0); -o-transform: translate(-50%,0); }
 <div id="outer"> <div id="inner">Foo foo</div> </div>

You can do it by using Flexbox which is a good technique these days.你可以使用Flexbox来做到这一点,这在当今是一种很好的技术。

For using Flexbox you should give display: flex;对于使用 Flexbox,你应该给出display: flex; and align-items: center;align-items: center; to your parent or #outer div element.到您的父级或#outer div 元素。 The code should be like this:代码应该是这样的:

 #outer { display: flex; align-items: center; }
 <div id="outer"> <div id="inner">Foo foo</div> </div>

This should center your child or #inner div horizontally.这应该使您的孩子或#inner div 水平居中。 But you can't actually see any changes.但你实际上看不到任何变化。 Because our #outer div has no height or in other words, its height is set to auto, so it has the same height as all of its child elements.因为我们的#outer div 没有高度,或者换句话说,它的高度设置为自动,所以它的高度与其所有子元素相同。 So after a little of visual styling, the result code should be like this:所以经过一点视觉造型后,结果代码应该是这样的:

 #outer { height: 500px; display: flex; align-items: center; background-color: blue; } #inner { height: 100px; background: yellow; }
 <div id="outer"> <div id="inner">Foo foo</div> </div>

You can see #inner div is now centered.您可以看到#inner div 现在居中。 Flexbox is the new method of positioning elements in horizontal or vertical stacks with CSS and it's got 96% of global browsers compatibility. Flexbox 是使用 CSS 在水平或垂直堆栈中定位元素的新方法,它具有 96% 的全球浏览器兼容性。 So you are free to use it and if you want to find out more about Flexbox visit CSS-Tricks article.所以你可以自由使用它,如果你想了解更多关于 Flexbox 的信息,请访问CSS-Tricks文章。 That is the best place to learn using Flexbox in my opinion.在我看来,这是学习使用 Flexbox 的最佳场所。

This worked for me:这对我有用:

#inner {
    position: absolute;
    margin: 0 auto;
    left: 0;
    width: 7%;
    right: 0;
}

In this code, you determine the width of the element.在此代码中,您确定元素的宽度。

 .outer { background-color: rgb(230,230,255); width: 100%; height: 50px; } .inner { background-color: rgb(200,200,255); width: 50%; height: 50px; margin: 0 auto; }
 <div class="outer"> <div class="inner"> margin 0 auto </div> </div>

I used Flexbox or CSS grid我使用了 FlexboxCSS 网格

  1. Flexbox弹性盒

     #outer{ display: flex; justify-content: center; }

  2. CSS grid CSS 网格

     #outer { display: inline-grid; grid-template-rows: 100px 100px 100px; grid-template-columns: 100px 100px 100px; grid-gap: 3px; }

You can solve the issue in many ways.您可以通过多种方式解决问题。

You can use one line of code, just text-align:center .您可以使用一行代码,只需text-align:center

Here's an example:这是一个例子:

 #inner { text-align: center; }
 <div id="outer" style="width:100%"> <div id="inner"><button>hello</button></div> </div>

I'm sorry but this baby from the 1990s just worked for me:很抱歉,这个 1990 年代的婴儿对我有用:

<div id="outer">  
  <center>Foo foo</center>
</div>

Am I going to hell for this sin?我会因为这个罪而下地狱吗?

div{
    width: 100px;
    height: 100px;
    margin: 0 auto;
}

For the normal thing if you are using div in a static way.如果您以静态方式使用 div ,则通常是这样。

If you want a div to be centered when div is absolute to its parent, here is example:如果您希望 div 在 div 对其父级是绝对的时居中,这里是示例:

.parentdiv{
    position: relative;
    height: 500px;
}

.child_div{
   position: absolute;
   height: 200px;
   width: 500px;
   left: 0;
   right: 0;
   margin: 0 auto;
}

You can add another div which has the same size of #inner and move it to the left by -50% (half of the width of #inner) and #inner by 50%.您可以添加另一个与#inner 大小相同的div,并将其向左移动-50%(#inner 宽度的一半)和#inner 50%。

 #inner { position: absolute; left: 50%; } #inner > div { position: relative; left: -50%; }
 <div id="outer"> <div id="inner"><div>Foo foo</div></div> </div>

In the previous examples they used margin: 0 auto , display:table and other answers used "with transform and translate".在前面的示例中,他们使用了margin: 0 autodisplay:table和其他使用“with transform and translate”的答案。

And what about just with a tag?仅使用标签又如何呢? Everyone knows there is a <center> tag which is just not supported by HTML5.每个人都知道 HTML5 不支持<center>标签。 But it works in HTML5.但它适用于 HTML5。 For instance, in my old projects.例如,在我的旧项目中。

And it is working, but now not only MDN Web Docs , but other websites are advising not to use it any more.它正在工作,但现在不仅是MDN Web Docs ,而且其他网站都建议不要再使用它。 Here in Can I use you can see notes from MDN Web Docs.Can I use你可以看到来自 MDN Web Docs 的注释。 But whatever, there is such a way.但无论如何,有这样的方法。 This is just to know.这只是要知道。 Always being noticed about something is so useful.总是被注意到某事是如此有用。

在此处输入图像描述

尝试这个:

<div style="position: absolute;left: 50%;top: 50%;-webkit-transform: translate(-50%, -50%);transform: translate(-50%, -50%);"><div>Example</div></div>

In my case I needed to center(on screen) a dropdown menu(using flexbox for it's items) below a button that could have various locations vertically.在我的情况下,我需要在一个可以垂直具有不同位置的按钮下方居中(在屏幕上)一个下拉菜单(使用 flexbox 作为它的项目)。 None of the suggestions worked until I changed position from absolute to fixed, like this:在我将位置从绝对位置更改为固定位置之前,这些建议都不起作用,如下所示:

 #outer { margin: auto; left: 0; right: 0; position: fixed; } #inner { text-align: center; }
 <div id="outer"> <div id="inner">Foo foo</div> </div>

The above codes makes the dropdown to always center on the screen for devices of all sizes, no matter where the dropdown button is located vertically.上面的代码使下拉菜单始终位于所有尺寸设备的屏幕中心,无论下拉按钮垂直位于何处。

There are several ways to achieve it: using "flex", "positioning", "margin" and others.有几种方法可以实现:使用“flex”、“positioning”、“margin”等。 Assuming #outer and #inner divs given in the question:假设问题中给出了#outer#inner div:

I would recommend using "flex"我建议使用“flex”

#outer {
   display: flex;
   justify-content: center;
   align-items: center;  /* if you also need vertical center */
}

Horizontal align using positioning使用定位水平对齐

#outer {
  position: relative;
}
#inner {
  position: absolute;
  left: 50%;
  translate: transformX(-50%)
}

Horizontal and vertical-align using positioning使用定位水平和垂直对齐

#outer {
  position: relative;
}
#inner {
  position: absolute;
  left: 50%;
  top: 50%;
  translate: transform(-50%, -50%)
}

Horizontal align using margin使用边距水平对齐

#inner {
 width: fit-content;
 margin: 0 auto;
}
#outer {postion: relative}
#inner {
    width: 100px; 
    height: 40px; 
    position: absolute;
    top: 50%;
    margin-top: -20px; /* Half of your height */
}

根据您的情况,最简单的解决方案可能是:

margin: 0 auto; float: none;

Yes, this is short and clean code for horizontal align.是的,这是用于水平对齐的简短而干净的代码。

.classname {
   display: box;
   margin: 0 auto;
   width: 500px /* Width set as per your requirement. */;
}

It is so simple.就是这么简单。

Just decide what width you want to give to the inner div and use the following CSS.只需决定要给内部 div 的宽度并使用以下 CSS。

CSS CSS

.inner{
  width: 500px; /* Assumed width */
  margin: 0 auto;
}

 <div id="outer" style="width:100%;margin: 0 auto; text-align: center;"> <div id="inner">Foo foo</div> </div>

After reading all the answers I did not see the one I prefer.阅读完所有答案后,我没有看到我喜欢的答案。 This is how you can center an element in another.这就是您可以将一个元素居中于另一个元素的方式。

jsfiddle - http://jsfiddle.net/josephtveter/w3sksu1w/ jsfiddle - http://jsfiddle.net/josephtveter/w3sksu1w/

<p>Horz Center</p>
<div class="outterDiv">
    <div class="innerDiv horzCenter"></div>
</div>
<p>Vert Center</p>
<div class="outterDiv">
    <div class="innerDiv vertCenter"></div>
</div>
<p>True Center</p>
<div class="outterDiv">
    <div class="innerDiv trueCenter"></div>
</div>
.vertCenter
{
    position: absolute;
    top:50%;
    -ms-transform: translateY(-50%);
    -moz-transform: translateY(-50%);
    -webkit-transform: translateY(-50%);
    transform: translateY(-50%);
}

.horzCenter
{
    position: absolute;
    left: 50%;
    -ms-transform: translateX(-50%);
    -moz-transform: translateX(-50%);
    -webkit-transform: translateX(-50%);
    transform: translateX(-50%);
}

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

.outterDiv
{
    position: relative;
    background-color: blue;
    width: 10rem;
    height: 10rem;
    margin: 2rem;
}
.innerDiv
{
    background-color: red;
    width: 5rem;
    height: 5rem;
}

Give some width to the inner div and add margin:0 auto;给内部div一些width并添加margin:0 auto; in the CSS property.在 CSS 属性中。

CSS CSS

#inner {
  display: table;
  margin: 0 auto; 
}

HTML HTML

<div id="outer" style="width:100%">  
  <div id="inner">Foo foo</div>
</div>

Use the below code.使用下面的代码。

HTML HTML

<div id="outer">
  <div id="inner">Foo foo</div>
</div>

CSS CSS

#outer {
  text-align: center;
}
#inner{
  display: inline-block;
}

You can add this code:您可以添加以下代码:

 #inner { width: 90%; margin: 0 auto; text-align:center; }
 <div id="outer"> <div id="inner">Foo foo</div> </div>

We could use the next CSS's class which allow center vertically and horizontally any element against its parent:我们可以使用下一个 CSS 类,它允许垂直和水平居中任何元素与其父元素:

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

Use this code:使用此代码:

<div id="outer">
    <div id="inner">Foo foo</div>
</div>

#inner {
  width: 50%;
  margin: 0 auto;
  text-align: center;
}

Use:利用:

<style>
  #outer{
    text-align: center;
    width: 100%;
  }
  #inner{
    text-align: center;
  }
</style>

This centralizes your inner div horizontally and vertically:这使您的内部 div 水平和垂直集中:

#outer{
    display: flex;
}
#inner{
    margin: auto;
}

For only horizontal align, change仅水平对齐,更改

margin: 0 auto;

and for vertical, change对于垂直,改变

margin: auto 0;

One of the easiest ways you can do it is by using display: flex .最简单的方法之一是使用display: flex The outer div just needs to have display flex, and the inner needs margin: 0 auto to make it centered horizontally.外部 div 只需要显示 flex,内部需要margin: 0 auto使其水平居中。

To center vertically and just center a div within another div, please look at the comments of the .inner class below要垂直居中并仅将 div 居中在另一个 div 中,请查看下面 .inner 类的注释

 .wrapper { display: flex; /* Adding whatever height & width we want */ height: 300px; width: 300px; /* Just so you can see it is centered */ background: peachpuff; } .inner { /* center horizontally */ margin: 0 auto; /* center vertically */ /* margin: auto 0; */ /* center */ /* margin: 0 auto; */ }
 <div class="wrapper"> <div class="inner"> I am horizontally! </div> </div>

CSS justify-content property CSS justify-content属性

It aligns the Flexbox items at the center of the container:它在容器的中心对齐Flexbox 项目:

#outer {
    display: flex;
    justify-content: center;
}

 #outer { display: grid; justify-content: center; }
 <div id="outer"> <div id="inner">hello</div> </div>
enter code here

I've seen lots and lots of answers and they are all outdated.我看过很多很多答案,它们都已经过时了。 Google already implemented a solution for this common problem, which centers the object literally in the middle no matter what happens, and YES it's responsive.谷歌已经为这个常见问题实施了一个解决方案,无论发生什么,它都会将对象放在中间,是的,它是响应式的。 So never do transform() or position manually ever again.所以永远不要再做transform()或手动position

.HTML .HTML

...
<div class="parent">
   <form> ... </form>
   <div> ... </div>
</div>

.CSS .CSS

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

I know I'm a bit late to answering this question, and I haven't bothered to read every single answer so this may be a duplicate.我知道我回答这个问题有点晚了,而且我没有费心阅读每一个答案,所以这可能是重复的。 Here's my take :这是我的看法

inner { width: 50%; background-color: Khaki; margin: 0 auto; }

Try this:尝试这个:

<div id="a">
    <div id="b"></div>
</div>

CSS: CSS:

#a{
   border: 1px solid red;
   height: 120px;
   width: 400px
}

#b{
   border: 1px solid blue;
   height: 90px;
   width: 300px;
   position: relative;
   margin-left: auto;
   margin-right: auto;
}

First of all: You need to give a width to the second div:首先:您需要为第二个 div 指定宽度:

For example:例如:

HTML HTML

<div id="outter">
    <div id="inner"Centered content">
    </div
</div>

CSS: CSS:

 #inner{
     width: 50%;
     margin: auto;
}

Note that if you don't give it a width, it will take the whole width of the line.请注意,如果您不给它一个宽度,它将占用该行的整个宽度。

Instead of multiple wrappers and/or auto margins, this simple solution works for me:这个简单的解决方案对我有用,而不是多个包装器和/或自动边距:

<div style="top: 50%; left: 50%;
    height: 100px; width: 100px;
    margin-top: -50px; margin-left: -50px;
    background: url('lib/loading.gif') no-repeat center #fff;
    text-align: center;
    position: fixed; z-index: 9002;">Loading...</div>

It puts the div at the center of the view (vertical and horizontal), sizes and adjusts for size, centers background image (vertical and horizontal), centers text (horizontal), and keeps div in the view and on top of the content.它将 div 放在视图的中心(垂直和水平),调整大小并调整大小,居中背景图像(垂直和水平),居中文本(水平),并将 div 保持在视图中和内容的顶部。 Simply place in the HTML body and enjoy.只需放置在 HTML body中即可享受。

The best way is using table-cell display (inner) that come exactly after a div with the display table (outer) and set vertical align for the inner div (with table-cell display) and every tag you use in the inner div placed in the center of div or page.最好的方法是使用表格单元格显示(内部),它恰好位于带有显示表格(外部)的 div 之后,并为内部 div 设置垂直对齐(带有表格单元格显示)和您在内部 div 中使用的每个标签放置在 div 或页面的中心。

Note: you must set a specified height to outer注意:您必须将指定的高度设置为外部

It is the best way you know without position relative or absolute, and you can use it in every browser as same.这是你知道的最好的方法,没有相对或绝对位置,你可以在每个浏览器中使用它。

 #outer{ display: table; height: 100vh; width: 100%; } #inner{ display: table-cell; vertical-align: middle; text-align: center; }
 <div id="outer"> <div id="inner"> <h1> set content center </h1> <div> hi this is the best way to align your items center </div> </div> </div>

HTML: HTML:

<div id="outer">
  <div id="inner">
  </div>
</div>

CSS: CSS:

#outer{
  width: 500px;
  background-color: #000;
  height: 500px
}
#inner{
  background-color: #333;
  margin: 0 auto;
  width: 50%;
  height: 250px;
}

Fiddle .小提琴

Add text-align:center;添加text-align:center; to parent div到父 div

#outer {
    text-align: center;
}

https://jsfiddle.net/7qwxx9rs/ https://jsfiddle.net/7qwxx9rs/

or或者

#outer > div {
    margin: auto;
    width: 100px;
}

https://jsfiddle.net/f8su1fLz/ https://jsfiddle.net/f8su1fLz/

Just simply Margin:0px auto :只是简单Margin:0px auto

 #inner{ display: block; margin: 0px auto; width: 100px; }
 <div id="outer" style="width:100%"> <div id="inner">Foo foo</div> </div>

You can do it in a different way.你可以用不同的方式来做。 See the below examples:请参阅以下示例:

1. First Method
#outer {
   text-align: center;
   width: 100%;
}
#inner {
   display: inline-block;
}


2. Second method
#outer {
  position: relative;
  overflow: hidden;
}
.centered {
   position: absolute;
   left: 50%;
}

 #inner { display: table; margin: 0 auto; }
 <div id="outer" style="width:100%"> <div id="inner">Foo foo</div> </div>

The main attributes for centering the div are margin: auto and width: according to requirements:使 div 居中的主要属性是margin: autowidth:根据要求:

.DivCenter{
    width: 50%;
    margin: auto;
    border: 3px solid #000;
    padding: 10px;
}

 #outer { width: 160px; padding: 5px; border-style: solid; border-width: thin; display: block; } #inner { margin: auto; background-color: lightblue; border-style: solid; border-width: thin; width: 80px; padding: 10px; text-align: center; }
 <div id="outer"> <div id="inner">Foo foo</div> </div>

I found a similar way with margin-left , but it can be left as well.我找到了与margin-left类似的方法,但也可以left

#inner {
    width: 100%;
    max-width: 65px; /* To adapt to screen width. It can be whatever you want. */
    left: 65px; /* This has to be approximately the same as the max-width. */
}
#inner {
  width: 50%;
  margin: 0 auto;
}

Add CSS to your inner div.将 CSS 添加到您的内部 div。 Set margin: 0 auto and set its width less than 100%, which is the width of the outer div.设置margin: 0 auto并设置它的宽度小于 100%,也就是外部 div 的宽度。

<div id="outer" style="width:100%"> 
    <div id="inner" style="margin:0 auto;width:50%">Foo foo</div> 
</div>

This will give the desired result.这将给出预期的结果。

Flexbox Center Horizontally and Vertically Center Align an Element Flexbox 水平居中和垂直居中对齐元素

 .wrapper {border: 1px solid #678596; max-width: 350px; margin: 30px auto;} .parentClass { display: flex; justify-content: center; align-items: center; height: 300px;} .parentClass div {margin: 5px; background: #678596; width: 50px; line-height: 50px; text-align: center; font-size: 30px; color: #fff;}
 <h1>Flexbox Center Horizontally and Vertically Center Align an Element</h1> <h2>justify-content: center; align-items: center;</h2> <div class="wrapper"> <div class="parentClass"> <div>c</div> </div> </div>

button {
  margin: 0 auto;
  width: fit-content;
  display: block;
}
// container should have set width (for example 100%)

 #outer { display:grid; place-items:center; }
 <div id="outer"> <div id="inner">Foo foo</div> </div>

I'd simply suggest using justify-content: center;我只是建议使用justify-content: center; when the container is displayed as flex.当容器显示为 flex 时。 and text-align: center;text-align: center; when it is about a text element.当它是关于文本元素时。

check the code below and modify as per the requirements.检查下面的代码并根据要求进行修改。

 #content_block { border: 1px solid black; padding: 10px; width: 50%; text-align: center; } #container { border: 1px solid red; width:100%; padding: 20px; display: flex; justify-content: center; }
 <div id="container"> <div id="content_block">Foo foo check</div> </div>

#outer{
  display: flex;
  width: 100%;
  height: 200px;
  justify-content:center;
  align-items:center;
}

 <html>

 *{ margin: 0; padding: 0; } #outer{ background: red; width: 100%; height: 100vh; display: flex; /*center For vertically*/ justify-content: center; flex-direction: column; /*center for horizontally*/ align-items: center; } #inner{ width: 80%; height: 40px; background: grey; margin-top:5px; }
 <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>horizontally center an element</title> </head> <body> <div id="outer"> <div id="inner">1</div> <div id="inner" style="background: green;">2</div> <div id="inner" style="background: yellow;">3</div> </div> </body> </html>

<div class="container">
<div class="res-banner">
<img class="imgmelk"  src="~/File/opt_img.jpg" >
</div>
</div>

css code CSS代码

.res-banner{
        width:309px;
        margin: auto;
        height:309px;
    }

Recap 2022回顾 2022

This is a very old question so I'm just trying to report the situation today:这是一个非常古老的问题,所以我只是想报告今天的情况:

  • CSS grid and flexbox are the best options you have for centering, horizontal or vertical; CSS grid 和 flexbox 是居中、水平或垂直的最佳选择;
  • margin:auto method works well if the inner content is not a box (inline-block is okay);如果内部内容不是一个框(inline-block 可以),margin:auto 方法效果很好;
  • margin 50% with transform:translateX(-50%) is brute force but works allright;使用 transform:translateX(-50%) 保留 50% 的边距是蛮力但可以正常工作;
  • same thing with absolute positions and translateX/Y is good for horizontal and vertical centering too, many dialogs use that, stretching height to 100vh;绝对位置和 translateX/Y 同样适用于水平和垂直居中,许多对话框都使用它,将高度拉伸到 100vh;
  • the good old text-align:center with inline-block still works旧的 text-align:center 与 inline-block 仍然有效
  • the ancient demon called "center tag" still works, actually it's the easiest way for horizontal centering.古老的恶魔叫做“中心标签”仍然有效,实际上它是水平居中最简单的方法。 Deprecated, feared & hated by many but still;被许多人弃用、恐惧和憎恨,但仍然;
  • tables (td tags, actually) can center beautifully, horizontal and vertical, but they're also called old hat;表格(实际上是 td 标签)可以很好地居中,水平和垂直,但它们也被称为旧帽子;
  • these last 2 will work in email templates too (they're HTML4) if you're unlucky enough to work on one.如果您不幸使用其中一个,那么最后两个也可以在电子邮件模板中使用(它们是 HTML4)。

That's what it looks like in 2022, and I hope we'll never need more than grids and flexboxes.这就是 2022 年的样子,我希望我们永远不需要网格和弹性盒。 Those guys are the answer to all our prayers in 1999.这些家伙是我们在 1999 年所有祈祷的答案。

You can horizontally center a <div> within another <div> by using text-align Property in CSS.您可以使用 CSS 中的text-align属性将一个<div>水平居中于另一个<div>中。

text-align: center is used to center the text of the outer div horizontally. text-align: center用于将外层div的文本水平居中。

text-align: right is used to align the text to the right. text-align: right用于将文本向右对齐。

text-align: left is used to align the text to the left. text-align: left用于将文本左对齐。

text-align: justify is used to stretch the lines so that each line has equal width. text-align: justify用于拉伸线条,使每条线的宽度相等。

 div.a { text-align: center; } div.b { text-align: left; } div.c { text-align: right; } div.d { text-align: justify; }
 <h1>The text-align Property</h1> <div class="a"> <h2>text-align: center:</h2> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam semper diam at erat pulvinar, at pulvinar felis blandit. Vestibulum volutpat tellus diam, consequat gravida libero rhoncus ut.</p> </div> <div class="b"> <h2>text-align: left:</h2> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam semper diam at erat pulvinar, at pulvinar felis blandit. Vestibulum volutpat tellus diam, consequat gravida libero rhoncus ut.</p> </div> <div class="c"> <h2>text-align: right:</h2> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam semper diam at erat pulvinar, at pulvinar felis blandit. Vestibulum volutpat tellus diam, consequat gravida libero rhoncus ut.</p> </div> <div class="d"> <h2>text-align: justify:</h2> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam semper diam at erat pulvinar, at pulvinar felis blandit. Vestibulum volutpat tellus diam, consequat gravida libero rhoncus ut.</p> </div>

<div id="outer">
  <div id="inner">Foo foo</div>
</div>



#outer{
     display:flex;
     align-items:center;
}

You can horizontally align any element using:您可以使用以下方法水平对齐任何元素:

<div align=center>
    (code goes here)
</div>

Or:或者:

<!-- css here -->
    .center-me {
        margin: 0 auto;
    }

<!-- html here -->
    <div class="center-me">
        (code goes here)
    </div>

Updated 2022 Centering Element Horizontally更新 2022 水平居中元素

1. Horizontally centering using flexbox 1.使用flexbox水平居中

To horizontally center a elements like (div) need to add display:flex and justify-content:center to the element css class.要水平居中像 (div) 这样的元素,需要将display:flexjustify-content:center添加到元素 css 类中。

<div class="center">
   <h1>I'm Horizontally center</h1>
</div>
.center{
   display:flex;
   justify-content:center;
}

2. Horizontally centering using margins 2. 使用边距水平居中

Below example shows how to horizontally center elements using margins and width .下面的示例显示了如何使用marginswidth水平居中元素。

.center{
    width:50%;
    margin:0 auto;
}

In the above code, have added width:50% and margin:0 auto so that the element equally splits the available space between the left and right margins.在上面的代码中,添加right width:50%margin:0 auto以便元素在left边距之间平均分割可用空间。

3. Horizontally centering using transform 3.使用transform水平居中

Below example shows how to horizontally center elements using position and transform properties.下面的例子展示了如何使用positiontransform属性使元素水平居中。

.center{
    position: absolute;
    left: 50%;
    transform: translateX(-50%);
}
  • Firstly added position:absolute , so that element comes out from the normal document flow.首先添加position:absolute ,使元素从正常的文档流中出来。
  • second we added left:50% , so that element moves forward 50% towards x-axis.其次,我们添加了left:50% ,以便元素向 x 轴向前移动50%
  • Third, we added transform:translateX(-50%) , so that element comes backward 50% and align it to center.第三,我们添加了transform:translateX(-50%) ,使元素向后移动 50% 并将其居中对齐。

I am sharing this answer for the designers who want to align their content both horizontally and vertically.我正在为想要水平和垂直对齐其内容的设计师分享这个答案。 Or you may say in the center of the web page.或者你可以说在网页的中央。 Please go to this site to download the file.到此站点下载文件。

CSS Code CSS 代码

.ver-hor-div {
    display: table-cell;
    vertical-align: middle;
    text-align: center;
}

You can use the link https://plnkr.co/edit/MQD5QHJe5oUVKEvHCz8p?p=preview您可以使用链接https://plnkr.co/edit/MQD5QHJe5oUVKEvHCz8p?p=preview

.outer{
      display: table;
      width: 100%;
      height: 100%;
}
.inner {
    vertical-align: middle;
}

Refer to https://v4-alpha.getbootstrap.com/examples/cover/参考https://v4-alpha.getbootstrap.com/examples/cover/

For a horizontally centered DIV:对于水平居中的 DIV:

#outer {
  width: 100%;
  text-align: center;
}
#inner {
  display: inline-block;
}
<div id="outer">
  <div id="inner">Foo foo</div>
</div>

I think this will be a solution:我认为这将是一个解决方案:

#outer {
    position: absolute;
    left: 50%;
}

#inner {
    position: relative;
    left: -50%;
}

Both elements must be the same width to function separately.两个元素必须具有相同的宽度才能单独运行。

can use a center tag for convenience为方便起见可以使用中心标签

   <div id="outer">
 <center> 
<div id="inner">Foo foo</div> 
</center> 
</div>

 <!DOCTYPE html> <html> <head> <title>Center</title> <style> .outer{ text-align: center; } .inner{ width: 500px; margin: 0 auto; background: brown; color: red; } </style> </head> <body> <div class="outer"> <div class="inner">This DIV is centered</div> </div> </body> </html>

Please try this.请试试这个。 It will work without the HTML center tag.它可以在没有 HTML 中心标签的情况下工作。

.outer {
    text-align: center;
    width: 100%
}
<div id="outer" style="width:100%">  
  <div id="inner" style="text-align:center">Foo foo</div>
</div>
<center>

我被已知的最简单的中心宠坏了?

</center>

Centering: Auto-width Margins居中:自动宽度边距

This box is horizontally centered by setting its right and left margin widths to "auto".此框通过将其左右边距宽度设置为“自动”来水平居中。 This is the preferred way to accomplish horizontal centering with CSS and works very well in most browsers with CSS 2 support.这是使用 CSS 实现水平居中的首选方式,并且在大多数支持 CSS 2 的浏览器中效果很好。 Unfortunately, Internet Explorer 5/Windows does not respond to this method - a shortcoming of that browser, not the technique.不幸的是,Internet Explorer 5/Windows 不响应这种方法——这是该浏览器的缺点,而不是技术的缺点。

There is a simple workaround.有一个简单的解决方法。 (A pause while you fight back the nausea induced by that word.) Ready? (在你抵抗那个词引起的恶心时停顿了一下。)准备好了吗? Internet Explorer 5/Windows incorrectly applies the CSS "text-align" attribute to block-level elements. Internet Explorer 5/Windows 错误地将 CSS“文本对齐”属性应用于块级元素。 Declaring "text-align:center" for the containing block-level element (often the BODY element) horizontally centers the box in Internet Explorer 5/Windows.为包含的块级元素(通常是 BODY 元素)声明“text-align:center”会使 Internet Explorer 5/Windows 中的框水平居中。

There is a side effect of this workaround: the CSS "text-align" attribute is inherited, centering inline content.这种变通方法有一个副作用:继承了 CSS“text-align”属性,使内联内容居中。 It is often necessary to explicitly set the "text-align" attribute for the centered box, counteracting the effects of the Internet Explorer 5/Windows workaround.通常需要为居中的框显式设置“文本对齐”属性,以抵消 Internet Explorer 5/Windows 变通方法的影响。 The relevant CSS follows.相关的 CSS 如下。

body {
    margin: 50px 0px;
    padding: 0px;
    text-align: center;
}

#Content {
    width: 500px;
    margin: 0px auto;
    text-align: left;
    padding: 15px;
    border: 1px dashed #333;
    background-color: #EEE;
}

http://bluerobot.com/web/css/center1.html http://bluerobot.com/web/css/center1.html

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

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