如何将绝对定位的HTML块元素居中? (相对于它的父亲?)

时间:2015-08-23 17:32:52

标签: html css

我有以下HTML:

<div id="parent" style="height: 300px; position: relative">
  <div id="child" style="width: 100px; height: 50px; bottom: 0; position: absolute">
     ... content ...
   </div>
</div>

在此HTML中,我使用绝对定位将#child置于#parent的底部。

但是,我还想将#child置于#parent之内。父级的宽度会根据其用例进行更改,因此我无法以像素为单位计算它并将一半像素(居中)应用于子级left属性。

text-align: center应用于#parent并不会使#child居中,因为它位于绝对位置。

text-align: center应用于#child孩子内容置于中,并且不影响其自身定位。

如果父级有时会动态更改其宽度,那么如何在没有JavaScript的情况下将#child置于#parent之内的任何想法?

6 个答案:

答案 0 :(得分:2)

定位孩子left:0right:0,并将margin设置为auto

&#13;
&#13;
#parent {
  height: 300px;
  position: relative;
  background: #ccc;
}
#child {
  width: 100px;
  height: 50px;
  bottom: 0;
  position: absolute;
  left: 0;
  right: 0;
  margin: auto;
  background: red;
}
&#13;
<div id="parent">
  <div id="child">
    ... content ...
  </div>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

.parent {
    position: relative;
    height: 300px; 
}
.child {
    width: 100px;
    height: 50px; 
    position: absolute;
    top: 50%;
    left: 50%;
    margin-left: -50px; /* the half of the element */
}

答案 2 :(得分:0)

实现这一目标的最简单方法是使用transform:

.parent {
  position: relative;
}
.child {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

另外,只是一个单挑......你的内联样式#child&amp; #parent缺少&#34;;&#34;最后。

答案 3 :(得分:0)

它适用于绝对定位元素的css:

#child {
 position: absolute;
 left:0; right:0;
 margin: 5px auto;
}

答案 4 :(得分:0)

使用flextable和margin auto可以使绝对定位元素居中

        #parent{
            position:relative;
            display: flex;
        }

        #child
        {
            margin:auto; 
        }

答案 5 :(得分:0)

你可以保持元素在通量中:

1)使用display: table ;属性(需要一个额外的元素,这里使用的身体)

&#13;
&#13;
html,
body {
  width: 100%;
  margin:0;
}
div {
  border:solid;
  }
body {
  display:table;
  }
#parent {
  display: table-cell;
  vertical-align: middle;
  width: 100%;
}
#child {
  margin: auto;
}
&#13;
<div id="parent" style="height: 300px; position: relative">
  <div id="child" style="width: 100px; height: 50px; ">
    ... content ...
  </div>
</div>
&#13;
&#13;
&#13;

2)使用显示器: flex ;财产(仅限年轻浏览器)。

&#13;
&#13;
div {
  border:solid;
  }

#parent, 
#child /* want to center child content too ? */{
  display: flex;
  justify-content:center;
  align-items:center;
}
&#13;
<div id="parent" style="height: 300px; position: relative">
  <div id="child" style="width: 100px; height: 50px; ">
    ... content ...
  </div>
</div>
&#13;
&#13;
&#13;