【问题标题】:How to center a component without knowing its width in Css如何在不知道 Css 宽度的情况下将组件居中
【发布时间】:2016-08-30 22:53:36
【问题描述】:

如何在不知道其宽度值的情况下使组件居中。我知道您可以通过在 css 中编写以下内容来将组件定位在中心:

Width: componentWidth; 
margin: auto;

但就我而言,这是一种通用样式(赋予不同类型的按钮,具有不同的价值)。

任何帮助将不胜感激

【问题讨论】:

标签: html css


【解决方案1】:

我建议在您的容器上使用 display:flexjustify-content:center

例如

HTML

<div class="container">
  <span class="content">Center!</span>
</div>
<hr />
<div class="container2">
  <span class="content2">Center 2!</span>
</div>

CSS

.container {
  display:flex;
  justify-content:center;
  border:solid 1px red;
}

.container2 {
  display:flex;
  height:200px;
  justify-content:center;
  align-items:center;
  border:solid 1px red;
}

Fiddle here

第二个容器是一个如何垂直居中的示例,作为额外的奖励。

【讨论】:

    【解决方案2】:

    margin: auto; 将在您为元素定义了一些固定宽度时工作,如果您有 dynamic 宽度,您可以使用 transform: translateX(-50%); 将您的元素水平居中(我假设这是您的想要),或者如果你想垂直居中,你可以添加translateY(-50%)

    例如:

    div {
      position: absolute;
      left: 50%;
      top: 50%;
      transform: translateX(-50%) translateY(-50%);
      /* specifying x and y separately on purpose so that you understand whats going 
         on and what you can remove what you don't need from the above snippet */
    }
    

    Demo

    如果你只想要水平居中的元素,请分别去掉 top: 50%translateY(-50%)。请注意,将absolute 定位元素嵌套在relative 定位元素中是一种很好的做法。

    【讨论】:

    • 可行,但不适用于所有浏览器(例如 Safari)
    • 这是正确答案。要使 Safari 兼容,请使用 -webkit-transform: translate(-50%, -50%);
    【解决方案3】:

    为了使margin: auto 工作,您还必须将block 作为显示类型。默认情况下,链接和按钮的显示类型为 inline-block,因此请使用您的样式中的 display: block; 覆盖它:

    .whatever-your-btn-class-is {
      margin: auto;
      width: componentWidth;
      display: block;
    }
    

    【讨论】:

      【解决方案4】:

      如果你想学老派,你可以在没有 CSS 或知道元素大小的情况下使用表格来做到这一点。

      <table width="100%">
      <tr>
          <td align="center"><!-- anything in here will be centered --></td>
      </tr>
      </table>
      

      这是一个例子

      https://jsfiddle.net/gxyyecdy/

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-04-17
        • 2012-05-04
        • 2023-03-02
        • 2013-03-03
        • 2012-08-20
        • 1970-01-01
        • 2010-12-21
        相关资源
        最近更新 更多