I can't understand why the following code does not make the image centered. Can you help me?
<div align="center" style="position:relative;">
<div style="position: absolute">
<img src="a.png"/>
</div>
</div>
You need to use auto margins and set left
and right
values if you want to center an absolutely positioned element.
#absolute-element{
left: 0;
right: 0;
margin: 0 auto;
}
使用绝对值时必须设置top和left属性
To center the image horizontally and vertically add left:0; right:0; top:0; bottom:0; margin: auto;
left:0; right:0; top:0; bottom:0; margin: auto;
<div style="position:relative; height: 100%; background: #eee;">
<div >
<img style="position: absolute; left:0; right:0; top:0; bottom:0; margin: auto;" src="http://placehold.it/350x150"/>
</div>
</div>
If you want horizontally center then you have to define left
and right
property.
Have a look the DEMO .
<div style="position:relative; border-top:1px solid red;">
<div style="position: absolute; left:50%; right:50%;">
<img src="http://placehold.it/100x100" />
</div>
</div>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.