我试图在粉红色的中间得到蓝色的容器,但似乎垂直对齐:中间;在这种情况下是没用的。

<div style="display: block; position: absolute; left: 50px; top: 50px;">
    <div style="text-align: left; position: absolute;height: 56px;vertical-align: middle;background-color: pink;">
        <div style="background-color: lightblue;">test</div>
    </div>
</div>

结果:

预期:

请建议我怎样才能做到这一点。

杰斯菲德尔


当前回答

垂直和水平居中:

.parent{
  height: 100%;
  position: absolute;
  width: 100%;
  top: 0;
  left: 0;
}
.c{
  position: absolute;
  top: 50%;
  left: 0;
  right: 0;
  transform: translateY(-50%);
}

其他回答

使用flex blox在你的绝对定位div居中它的内容。

参见示例https://plnkr.co/edit/wJIX2NpbNhO34X68ZyoY?p=preview

.some-absolute-div {    
  display: -webkit-box;
  display: -webkit-flex;
  display: -moz-box;
  display: -moz-flex;
  display: -ms-flexbox;
  display: flex;

  -webkit-box-pack: center;
  -ms-flex-pack: center;
  -webkit-justify-content: center;
  -moz-justify-content: center;
  justify-content: center;

  -webkit-box-align: center;
  -ms-flex-align: center;
  -webkit-align-items: center;
  -moz-align-items: center;
  align-items: center;
}

编辑:10/22现在,显示flex或网格被广泛实现,我建议使用其中一个(display:table/table-cell仍然可以工作,如果你需要与旧的或外来的浏览器兼容,比如我的电视…)

flex

。{ 位置:绝对的; 左:50 px; 上图:50 px; } 。b { 显示:flex; 对齐项目:中心; 背景颜色:粉色; 高度:56 px; } c { background - color: lightblue; } /*移动flex演示*/ .a.b{左:100 px} 你甚至需要更少的加价 < div class = " " > < div class = " b " > < div class = " c " > < / div >测试 < / div > < / div > <div class="a b"> < div class = " c " > < / div >测试 < / div >

网格(与此相似)

。{ 位置:绝对的; 左:50 px; 上图:50 px; } 。b { 显示:网格; 对齐项目:中心; 背景颜色:粉色; 高度:56 px; } c { background - color: lightblue; } /*移动网格演示*/ .a.b{左:100 px} 你甚至需要更少的加价 < div class = " " > < div class = " b " > < div class = " c " > < / div >测试 < / div > < / div > <div class="a b"> < div class = " c " > < / div >测试 < / div >


原始答案02/2015(仍然在任何地方都有效)用于非常老的或外来的浏览器,还没有实现flex或网格

你可以使用display:table/table-cell;

。{ 位置:绝对的; 左:50 px; 上图:50 px; 显示:表; } 。b { text-align:左; 显示:表格单元; 高度:56 px; vertical-align:中间; 背景颜色:粉色; } c { background - color: lightblue; } < div class = " " > < div class = " b " > <div class="c" >test</div> < / div > < / div >

垂直和水平居中:

.parent{
  height: 100%;
  position: absolute;
  width: 100%;
  top: 0;
  left: 0;
}
.c{
  position: absolute;
  top: 50%;
  left: 0;
  right: 0;
  transform: translateY(-50%);
}

仅适用于垂直中心

< span style=" font - family:宋体;位置:相对,高度:56px,背景-颜色:粉色;" > < span style=" font - family:宋体;变换:translateY (-50%);“>测试< / div > < / div >

我总是这样做,这是一个非常简短和容易的代码,水平和垂直居中

.center { 位置:绝对的; 上图:50%; 左:50%; 转换:翻译(-50%,-50%); } <div class="center">Hello居中世界!< / div >

用这个:

.Absolute-Center {
    margin: auto;
    position: absolute;
    top: 0; left: 0; bottom: 0; right: 0;
}

参考这个链接:https://www.smashingmagazine.com/2013/08/absolute-horizontal-vertical-centering-css/