垂直居中一个浮动的元素

it2024-01-04  64

如何垂直居中一个浮动的元素

方法一:已知元素宽高

div { background: #6699ff; width: 100px; height: 100px; /* 如果有父元素,父元素需要相对定位 */ position: absolute; top: 50%; left: 50%; /* 相对于父元素二分之一的高和宽 (自适应最好用百分比表示单位)*/ margin: -50%, 0, 0, -50%; /* 里面文字垂直居中 */ text-align: center; line-height: 100px; }

方法二:未知元素的高宽

div { width: 200px; height: 200px; background: #6699ff; margin: auto; /* 父元素需要相对定位 */ position: absolute; left: 0; top: 0; bottom: 0; right: 0; }

在div中垂直居中一个img图片

div { width: 500px; height: 500px; border: 1px solid red; position: relative; } img { width: 200px; height: 200px; position: absolute; left: 50%; top: 50%; margin-left: -100px; margin-top: -100px; }
最新回复(0)