Q
水平居中绝对元素
0
A
回答
3
你需要给一个width
属性为margin: auto
(中心)工作。
.container-box p {
position:absolute;
width: 25%; //add this
margin:auto;
...
}
此外另一个主要问题是,p
是中心对准到所述容器(.container-box
),而不是图像。 确保图像覆盖整个容器。你可以做到这一点的
.container-box img {
width: 100%;
}
现在它看起来像文本是在图像的中心,但在文字文本是在容器的中心,你的图像扩展到整个容器。
+0
'width'如何在这里工作,因为父元素/ img是未知的。 – Nofel
+0
图像不是这里的父母,'.container-box'是。因此,使图像覆盖整个div,然后它会看起来像文字在图像的中心 –
0
.container-box p{
position:absolute;
margin:auto;
width: 200px;
...
}
也宽100%的图像。
.container-box img{
width: 100%;
}
入住这款改装版Codepen
1
您可以用定位做到这一点:
* {margin:0;box-sizing:border-box}
.container-box {
display: inline-block; /* can also use inline-flex */
position: relative; /* since one of the children is positioned absolute */
}
.container-box > img {
display: block; /* removes bottom margin/whitespace */
max-width: 100%; /* horizontal responsiveness */
max-height: 100vh; /* vertical responsiveness */
}
.container-box > p {
position: absolute; /* positioned relative to its parent */
top: 50%; /* moved down by 50% of the parents height */
left: 50%; /* moved right by 50% of the parents width */
transform: translate(-50%,-50%); /* moved left and up by half of its width and height to achieve the perfect center */
height: 40px;
background: Gray;
color: #fff;
padding: 10px;
}
<div class="container-box">
<img src="https://placeimg.com/640/480/any" alt="">
<p>This is a temp. Image.</p>
</div>
0
使用左起:50%以及顶部:50%。我清理了一点CSS
.container-box p{
position:absolute;
height:40px;
background:grey;
color:white;
padding:10px;
box-sizing:border-box;
display:table;
left: 50%;
top: 50%;
}
相关问题
- 1. 水平居中元素内的元素
- 2. div中的水平居中元素
- 3. 水平居中div中的元素
- 4. 居中div元素水平和垂直
- 5. 如何将li元素水平居中
- 6. 这是将绝对定位元素水平居中的有效方法吗?
- 7. 如何将100%宽度div内的绝对定位元素水平居中?
- 8. 块元素,水平居中对齐和最小宽度可能
- 9. 水平居中对齐内嵌html元素
- 10. 如何仅使用父元素对HTML进行水平居中?
- 11. 居中对齐水平div
- 12. 水平居中水平ItemsControl
- 13. 居中绝对定位元素
- 14. 居中响应绝对定位元素
- 15. 水平居中
- 16. 水平居中
- 17. bootstrap水平对齐元素
- 18. 无法在IE中获得水平居中的绝对div
- 19. 不是水平居中,因为绝对位置
- 20. 以绝对格式水平居中定位图像
- 21. 需要帮助水平居中绝对定位的DIV
- 22. 垂直和水平居中文本没有绝对定位
- 23. 水平居中UL
- 24. 居中水平UL
- 25. 在div中水平对齐HTML元素
- 26. div元素与绝对垂直,水平浮动
- 27. 水平定位两个绝对元素而不使用javascript
- 28. 水平滚动绝对定位的元素?
- 29. 水平浮动容器内的绝对定位元素?
- 30. 绝对定位元素的垂直和水平定位
你必须根据'.container-box'的宽度来做。 '.container-box'的左边'.container-box'的50%。那会做。 –
https://codepen.io/anon/pen/LLbENv检查:D –