在css

时间:2018-01-09 06:19:50

标签: css

plunkr链接为https://plnkr.co/edit/mv3lL1vwu2LxoeFZw0TX

我想将div放在页面的中心(垂直和水平)。 div有一个按钮,该按钮应位于div的中心。我在Vertically center in viewport using CSS找到了一个解决方案,但它对我不起作用。另外,我想创建两个单独的规则,一个用于垂直对齐,一个用于水平对齐,并将它们一起使用(或单独使用),以便我可以选择哪个元素应该以哪种方式对齐。

我不想使用Flex,Bootstrap等,因为我正在尝试理解CSS概念。

水平对齐规则很简单。

.center-horizontally-common-styles {
    display: block;
    margin: auto auto;
}

垂直对齐规则是(从SO链接修改)

.centre-vertical-common-styles {
   position: fixed;
    right: 50%; 
    top: 50%; 
    transform: translateY(-50%);
    transform: translateX(50%);
}


.debug-border-common-styles {
    border: 3px solid black;
    height:40px;
    width:200px;
}

HTML

<div class="debug-border-common-styles centre-vertical-common-styles center-horizontally-common-styles">
    <button type="button"> Click Me! </button>
</div>

我的理解是right: 50%; top: 50%;将使用浏览器的窗口(视口?)作为参考,并将div的上边缘和右边缘移动到该位置是浏览器各自边缘位置的50%标记。 TranslateYTranslateX现在应该分别将div向上(-50%)向左移动(50%),以将按钮的中心对齐到页面的中间位置以按钮为中心。我面临的问题是:

1)translateY似乎不起作用。如果我将div的高度更改为200px。 div开始向下生长(即它的上边缘似乎是固定的!)如果宽度改为200px,它就不会发生。

.debug-border-common-styles {
    border: 3px solid black;
    height:200px;
    width:200px;
}

2)div内的按钮不在div的中心。我为按钮创建了以下css规则,但translateY似乎也不适用于此。

.centre-button-vertical-common-styles {
   position: absolute; /*use absolute so that the origin is no the parent div*/
   right: 50%; 
   top: 50%; 
   transform: translateY(-50%);
   transform: translateX(50%);
}

3)理想情况下,我想创建两个单独的规则,例如.center-vertical和.center-horizo​​ntal,并将它们组合起来以使用所需的效果。但是,如果我做了类似的事情,它就不起作用了。是否可以创建两个单独的规则?

.center-horizontally-common-styles {
    display: block;
    margin: auto auto;
}

此处不使用,因为横向规则应将项目置于中间

.centre-button-vertical-common-styles {
   position: absolute;
   top: 50%; 
   transform: translateY(-50%);
}

1 个答案:

答案 0 :(得分:0)

兄弟,你需要很少的风格箭头。这样做:))

 .centre-vertical-common-styles {
       position: fixed;
        left: 50%; 
        top: 50%; 
        transform: translate(-50%, -50%);
    }
    .debug-border-common-styles {
        border: 3px solid black;
        height:40px;
        width:200px;
        display:flex;
        align-items:center;
        justify-content:center;
    }
相关问题