css3:水平地将translateX转换为中心元素 [英] css3: translateX to center element horizontally

查看:254
本文介绍了css3:水平地将translateX转换为中心元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图水平居中一个元素: jsfiddle

I'm trying to center horizontally an element: jsfiddle

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

在孩子身上,我现在有以下css,它没有居中:

On the child I have now the following css which doesn't center:

transform: translateX(50%);

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

Unfortunately the 50% is taken from the #child and not the parent. Is there a way to center this element using transforms (I know I can center it using, for example '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;
}


推荐答案

你错过了一个职位亲属在你的父母身上,在孩子的位置上保持绝对,在左边和上边的值上有助于抵消孩子。

You were missing a position relative on your parent, position absolute on the child and the left and top values to help offset the child.

DEMO 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;
}

这篇关于css3:水平地将translateX转换为中心元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆