gpt4 book ai didi

html - 将显示为表格且绝对定位的 div 居中

转载 作者:行者123 更新时间:2023-11-28 17:54:51 25 4
gpt4 key购买 nike

正如标题所暗示的,我需要知道如何将应用了以下 CSS 规则的 div 居中:

display: table;
position: absolute;

div 应该正好在视口(viewport)的中间,并且按照 display: table; 的惯例,它应该是它的内容的大小。

最佳答案

HTML

<div class="center"></div>

如果表格的高度和宽度固定为 400px,那么您可以使用此 css:

.center {
display:table;
position:absolute;
height:400px;
width:400px;
background:red;
left:50%;
margin-left:-200px; <---- half of width
top:50%;
margin-top:-200px; <---- half of height
}

DEMO WITH CSS

如果表格具有动态高度和/或动态宽度,那么您可以使用此 jquery:

$('.center').css({
'left': $(window).width() / 2 - $('.center').width() / 2,
'top': $(window).height() / 2 - $('.center').height() / 2
});

DEMO WITH JS

关于html - 将显示为表格且绝对定位的 div 居中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21498952/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com