使用 CSS 将 div 居中的最佳且最简单的方法是什么?

问题描述 投票:0回答:1

我想将包含一些信息的 div 居中。对于网站上的用户。要求是无论浏览器的屏幕尺寸是多少,dic 都应位于中心,并且始终位于顶部。

我尝试过 margin:auto。这是一个好的做法吗?

html css sass
1个回答
-1
投票

有几种方法可以做到这一点。有些方法是这样的:

方法一:使用带有top和left属性的固定位置。

.center-div {
    position: fixed;  /* Fixed positioning so it's always on top */
    top: 50%;         /* Center vertically */
    left: 50%;        /* Center horizontally */
    transform: translate(-50%, -50%);  /* Adjust for the div's own dimensions */
    /* Your other styles here */
}

方法2:使用Flex属性:

.center-div-flex {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh; /* Full height of the viewport */
    position: fixed; /* Fixed positioning so it's always on top */
}

方法3:使用CSS网格:

.center-div-grid {
    display: grid;
    place-items: center;
    height: 100vh; /* Full height of the viewport */
    position: fixed; /* Fixed positioning so it's always on top */
}

您可以选择以上任意一种方式。

© www.soinside.com 2019 - 2024. All rights reserved.