为什么在HTML中居中这么难?

时间:2015-06-27 18:19:21

标签: html css center

为什么这段代码不能将所有三个元素都放在外部div中?



.center 
{
  margin-left: auto;
  margin-right: auto;
  width: 70%;
}

<div class="center">
  <h1 class="center">Headline</h1>

  <div class="center"><span>Some text</span></div>

  <form class="center">
    <button>Button</button>
  </form>
</div>
&#13;
&#13;
&#13;

如何在不指定绝对值的情况下执行此操作? 为什么用HTML margin-left: auto;margin-right: auto;这样的黑客来区分HTML中的div是如此困难?

6 个答案:

答案 0 :(得分:2)

只需添加text-align: center

即可

这是一个例子 https://jsfiddle.net/txtz8duL/

.center {
  margin-left: auto;
  margin-right: auto;
  width: 70%;
  text-align: center;  
}

还有一些变化: https://css-tricks.com/centering-css-complete-guide/

答案 1 :(得分:1)

要使文本或内嵌元素居中对齐,您只需使用text-align: center;

即可

自动边距设置为使用内联块或块级元素对齐某些固定宽度的元素。

因此,在您的情况下,以下中心是div元素,而不是文本:

.center {
  margin-left: auto;
  margin-right: auto;
  width: 70%;
} 

添加text-align:center也会对齐文本:

.center {
  margin-left: auto;
  margin-right: auto;
  width: 70%;
  text-align: center;
}

&#13;
&#13;
  .center {
 margin-left: auto;
 margin-right: auto;
 width: 70%;
 text-align: center;
}
&#13;
<div class="center">
  <!-- container -->
  <h1 class="center">Headline</h1>

  <div class="center">Some text</div>

  <form class="center">
    <button>Button</button>
  </form>
</div>
&#13;
&#13;
&#13;

答案 2 :(得分:1)

Here就是一个例子,这就是你要找的东西吗?

Here是中心元素的好指南

我认为你应该将元素分开,而不是尝试使用一个适合所有类的类,特别是当你想引用div和文本时,它可能会随着你扩展项目而变得更脏。但是,上面的示例使用了您的代码,因为您似乎想要为所有项使用相同的类。我使用display: block以防元素不是块项。

以上是项目的中心。

请记住

CSS

.center {
  display: block;
  width: 70%;
  text-align: center;
  margin: 0 auto;
}

答案 3 :(得分:1)

你可以使用text-align来集中这样的东西: <h1 style="text-align:center"> Sample Heading</h1>

答案 4 :(得分:0)

首先,您可以使用<center>元素将其内容与中心对齐。

不幸的是,到目前为止,CSS无法完全重现<center>布局管理器。

&#13;
&#13;
<center>
  <!-- container -->
  <h1 class="center">Headline</h1>

  <div class="center">Some text</div>

  <form class="center">
    <button>Button</button>
  </form>
</center>
&#13;
&#13;
&#13;

更新:技术上{+ 1}}在HTML5中已弃用,但适用于所有浏览器。并且一直有效,直到CSS没有匹配功能。

但你可能会对此感到满意:

&#13;
&#13;
<center>
&#13;
.center {
  text-align:center;
}
&#13;
&#13;
&#13;

答案 5 :(得分:0)

当使用属性为auto的边距时,您需要输入固定值(非百分比)作为宽度。

例如,如果您将百分比更改为px,cm,in或em值,则代码将起作用。

        .center
        {
            margin-left: auto;
            margin-right: auto;
            width: 70px;
        }

https://jsfiddle.net/s1napggb/

但是,为了使具有浮动值的元素居中,需要使用flexbox,CSS媒体查询或一些Javascript。

相关问题