简体   繁体   English

为什么CSS不会将`div`元素居中?

[英]Why doesn't this CSS center the `div` element?

Why doesn't this CSS center the container div ? 为什么这个CSS不能将容器div居中?

The JSFiddle is here (ignore the random JQuery): JSFiddle在这里(忽略随机JQuery):

http://jsfiddle.net/evamvid/7SW3L/20/ http://jsfiddle.net/evamvid/7SW3L/20/

Here's the "preview": 这是“预览”:

jsfiddle.net/evamvid/7SW3L/20/embedded/result/ jsfiddle.net/evamvid/7SW3L/20/embedded/result/

Because it doesn't have a defined width (and is 100% wide by default so it is centered). 因为它没有定义的宽度(默认为100%宽度,所以居中)。

You can either explicitly set the width to be the width of the blocks combined, or you can set the .container to inline-block and have it's container use text-align: center . 您可以将width显式设置为组合的块的宽度,也可以将.container设置为inline-block ,并使其容器使用text-align: center

body {
  text-align: center;
}

.container{
  display: inline-block;
}

Demo 演示版

Note: I've put text-align: center on the body for demo purposes. 注意:为了演示目的,我将text-align: center放置在body In reality, I'd suggest adding another container <div> so you don't have your entire body text-aligned to the center. 实际上,我建议添加另一个容器<div>以免整个正文文本居中对齐。

since you are using display: block , you can use text-align:center; 由于您使用display: block ,因此可以使用text-align:center; to center the elements 使元素居中

UPDATED FIDDLE 更新场

Just give width to the div. 只需给div加上宽度即可。 Calculate the total width it will take for the inner boxes and set the with to the div. 计算内部框所需的总宽度,并将with设置为div。 If you dont want to give it a width then search for the Table layout options for div. 如果不想给它一个宽度,则搜索div的Table布局选项。

.container{
  margin: 0 auto;
  width: 759px;
}

Just check this jsFiddle http://jsfiddle.net/shinde87sagar/7SW3L/26/ 只需检查此jsFiddle http://jsfiddle.net/shinde87sagar/7SW3L/26/

It is not happening because you have not given width to .container . 这没有发生,因为您没有给.container指定宽度。 By default, div takes 100% width. 默认情况下, div宽度为100%。 You need to either give width to .container or give it text-align:center as inside .container your divs are inline. 您需要给.container宽度,或者给它text-align:center作为.container内部的div内联。

DEMO using width here. 演示在这里使用宽度。

DEMO using center here. DEMO使用中心在这里。

YOUR EXAMPLE REVISED HERE * Read my comments 在这里修改您的示例* 阅读我的评论

DEMO 演示

You had some issues: 您遇到了一些问题:

.container{
  width:758px;        /* Set a width */
  /* display:block */ /* DIVs ARE ALREADY BLOCK LEVEL ELEMENTS */
  margin: 0 auto;
}

Or simply use 或简单地使用

.container{
  text-align:center;
}

DEMO 演示

Add following. 添加以下内容。

.container{
 text-align: center;
}

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

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