在下面的代码中,如何将一个固定位置的 div 水平居中?我已经尝试了几种方法,但没有一种方法可以正确地放在中心。
我试图让 div 距离顶部 100px,并且水平居中。
<!DOCTYPE HTML>
<html>
<head>
<title> New Document </title>
<style type="text/css">
.myDiv {
position: fixed;
top:100px;
left:auto;
padding:10px;
background-color: blue;
color: white;
}
</style>
</head>
<body>
<div class="myDiv">Something went wrong. God save the Queen!</div>
</body>
</html>
最佳答案
如果你事先不知道你的 div 的宽度(或者如果你不能设置它)你可以使用 transform
属性:
.myDiv {
position: fixed;
...
left: 50%;
-webkit-transform: translate(-50%, 0);
-moz-transform: translate(-50%, 0);
transform: translate(-50%, 0);
}
关于html - 水平居中具有固定位置的div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21186504/