如何将绝对定位的元素居中在div中?
我需要在窗口中央放置一个div
(与position:absolute;
)元素。 但是我遇到问题了,因为宽度是未知的 。
我试过这个。 但它需要调整,因为宽度是响应。
.center {
left: 50%;
bottom:5px;
}
有任何想法吗?
<body>
<div style="position: absolute; left: 50%;">
<div style="position: relative; left: -50%; border: dotted red 1px;">
I am some centered shrink-to-fit content! <br />
tum te tum
</div>
</div>
</body>
这适用于我:
#content {
position: absolute;
left: 0;
right: 0;
margin-left: auto;
margin-right: auto;
width: 100px; /* Need a specific value to work */
}
<body>
<div>
<div id="content">
I'm the content
</div>
</div>
</body>
响应式解决方案
一般来说,如果您不需要支持IE8或更低版本,则此方法适用于响应式设计或未知尺寸 。
.centered-axis-x {
position: absolute;
left: 50%;
transform: translate(-50%, 0);
}
.outer {
position: relative; /* or absolute */
/* unnecessary styling properties */
margin: 5%;
width: 80%;
height: 500px;
border: 1px solid red;
}
.inner {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
/* unnecessary styling properties */
max-width: 50%;
text-align: center;
border: 1px solid blue;
}
<div class="outer">
<div class="inner">I'm always centered<br/>doesn't matter how much text, height or width i have.<br/>The dimensions or my parent are irrelevant as well</div>
</div>
链接地址: http://www.djcxy.com/p/13227.html
上一篇: How to center absolutely positioned element in div?
下一篇: CSS center text (horizontally and vertically) inside a div block