cssdiv垂直居中(CSS元素水平垂直居中的方式)

1、已知子元素的高度和宽度,父元素相对定位,子元素绝对对定位。

<div class="parent"> <div class="child">子元素</div> </div>

.parent { border: 1px solid #888; width: 300px; height: 300px; padding: 20px; position: relative; } .child { background-color: #f40; width: 150px; height: 150px; position: absolute; left: calc(50% - 75px); top: calc(50% - 75px); }

2、子元素的高度和宽度不知,父元素相对定位,子元素绝对定位,然后利用CSS3的transform属性。

div 垂直居中

.parent { border: 1px solid #888; width: 300px; height: 300px; padding: 20px; position: relative; } .child { background-color: #f40; position: absolute; transform: translateX(-50%) translateY(-50%); left: 50%; top: 50%; }

3、子元素的高度和宽度不知,利用flex布局。

.parent { border: 1px solid #888; width: 300px; height: 300px; padding: 20px; display: flex; align-items: center; justify-content: center; } .child { background-color: #f40; }

您可以还会对下面的文章感兴趣

最新评论

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

使用微信扫描二维码后

点击右上角发送给好友