我有以下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
,如果父级有时会动态更改它的宽度?
子项定位left:0
并right:0
,并将margin
设置为 auto
。
#parent {
height: 300px;
position: relative;
background: #ccc;
}
#child {
width: 100px;
height: 50px;
bottom: 0;
position: absolute;
left: 0;
right: 0;
margin: auto;
background: red;
}
<div id="parent">
<div id="child">
... content ...
</div>
</div>
.parent {
position: relative;
height: 300px;
}
.child {
width: 100px;
height: 50px;
position: absolute;
top: 50%;
left: 50%;
margin-left: -50px; /* the half of the element */
}
实现此目的的最简单方法是使用 transform:
.parent {
position: relative;
}
.child {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
另外,只是一个提醒...#child & #parent 的内联样式末尾缺少";"。
您可以将元素保持在通量内:
1(使用显示:表;属性(需要一个额外的元素,这里身体是这样使用的(
html,
body {
width: 100%;
margin:0;
}
div {
border:solid;
}
body {
display:table;
}
#parent {
display: table-cell;
vertical-align: middle;
width: 100%;
}
#child {
margin: auto;
}
<div id="parent" style="height: 300px; position: relative">
<div id="child" style="width: 100px; height: 50px; ">
... content ...
</div>
</div>
2(使用显示:柔性;属性(仅限年轻浏览器(。
div {
border:solid;
}
#parent,
#child /* want to center child content too ? */{
display: flex;
justify-content:center;
align-items:center;
}
<div id="parent" style="height: 300px; position: relative">
<div id="child" style="width: 100px; height: 50px; ">
... content ...
</div>
</div>
它与这个 css 一起用于绝对定位的元素:
#child {
position: absolute;
left:0; right:0;
margin: 5px auto;
}
- 请参阅本教程:http://coursesweb.net/css/center-fixed-absolute-element_cs
使用弹性和边距自动可以将绝对定位的元素居中
#parent{
position:relative;
display: flex;
}
#child
{
margin:auto;
}