【问题标题】:css3: translateX to center element horizontallycss3: translateX 水平居中元素
【发布时间】:2013-12-30 13:57:50
【问题描述】:

我正在尝试将元素水平居中:jsfiddle

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

在孩子身上,我现在有以下不居中的 css:

transform: translateX(50%);

不幸的是,50% 来自#child 而不是父母。有没有办法使用转换来使这个元素居中(我知道我可以使用它来居中,例如'left')?

这里是 css 的完整列表

#parent {
    width: 300px
    height: 100px;
    background-color: black;
    border: 1px solid grey;
}
#child {
    height: 100px;
    width: 20px;
    -webkit-transform: translateX(50%);
    background-color:red;
}

【问题讨论】:

  • 你在#parent css中有什么?

标签: html css transform centering


【解决方案1】:

您缺少父级的相对位置、子级的绝对位置以及帮助抵消子级的 left 和 top 值。

演示http://jsfiddle.net/nA355/6/

#parent {
    width: 300px;
    height: 100px;
    background-color: black;
    border: 1px solid grey;
    position: relative;
}
#child {
    position: absolute;
    height: 100px;
    width: 20px;
    left: 50%;
    top: 50%;
    -webkit-transform: translateX(-50%) translateY(-50%);
    -moz-transform: translateX(-50%) translateY(-50%);
    transform: translateX(-50%) translateY(-50%);
    background-color:red;
}

【讨论】:

  • 在我的情况下,我想使用变换移动#child。混合绝对位置和变换使其变得复杂。例如,给定您的解决方案,您将如何将孩子向左移动 10 像素?这就是为什么我一直在寻找没有绝对定位的解决方案。
  • 左边距:-10px; ?
【解决方案2】:

我使用这种技术在“text-align:center;”的情况下水平对齐一些元素不能正常工作。

 position:relative; 
 left:50%;
 transform:translateX(-??em) /*or -??px or other unit of measure */

……“??”必须根据元素的宽度进行调整。我知道这有点 hacky,但似乎可以在我迄今为止尝试过的屏幕上工作。

在你的小提琴中,应用这种技术,我得到:

#parent {
    width: 300px
    height: 100px;
    background-color: black;
    border: 1px solid grey;
}
#child {
    position:relative;
    height: 100px;
    width: 20px;
    left:50%;
    transform: translateX(-10px); /*or  transform: translateX(-50%);*/
    -webkit-transform: translateX(-10px);/*or  -webkit-transform: translateX(-50%); */
    -ms-transform: translateX(-10px);/*or -ms-transform: translateX(-50%);*/
    background-color:red;
}

它使子 div 水平居中。

【讨论】:

    【解决方案3】:

    你可以通过 display flex 和 justify-content 来做到这一点。

    示例:http://jsfiddle.net/ugw9o3qp/1/

    #parent {
        display: flex;
        justify-content: center;
        width: 300px;
        height: 100px;
        background-color: black;
        border: 1px solid grey;
    }
    #child {
        height: 100px;
        width: 20px;
        background-color:red;
    }
    

    【讨论】:

      【解决方案4】:

      如果不想设置子元素的宽度

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

      【讨论】:

        猜你喜欢
        • 2014-06-20
        • 2010-09-11
        • 2015-05-28
        • 2022-08-10
        相关资源
        最近更新 更多