我想将包含一些信息的 div 居中。对于网站上的用户。要求是无论浏览器的屏幕尺寸是多少,dic 都应位于中心,并且始终位于顶部。
我尝试过 margin:auto。这是一个好的做法吗?
有几种方法可以做到这一点。有些方法是这样的:
方法一:使用带有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 */
}
您可以选择以上任意一种方式。