在下面的代码中,如何将具有固定位置的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>
答案 0 :(得分:4)
如果您事先不知道div的宽度(或者如果您不能设置它),您可以使用transform
属性:
.myDiv {
position: fixed;
...
left: 50%;
-webkit-transform: translate(-50%, 0);
-moz-transform: translate(-50%, 0);
transform: translate(-50%, 0);
}
答案 1 :(得分:2)
答案 2 :(得分:0)
如果div具有特定宽度,请尝试添加:
width: somevalue;
left: 50%;
margin-left: -somevalue/2;
答案 3 :(得分:0)
如果你修改它的宽度,任何值(可以是百分比),你可以这样做:
width: 250px;
position: fixed;
left: 50%;
margin-left: -125px; /* 250 / 2 */
如果你选择百分比,那就更简单了:
width: 50%;
position: fixed;
left: 25%; /* (100 - width) / 2 */
工作小提琴:JSFiddle
答案 4 :(得分:0)
你走了。
<强> WORKING DEMO 强>
HTML代码:
<div class="myDiv">Something went wrong. God save the Queen!</div>
CSS代码:
.myDiv {
background-color: #0000FF;
color: #FFFFFF;
left: auto;
margin: 0 auto;
padding: 10px;
position: fixed;
text-align: center;
top: 100px;
width: calc(100% - 37px);
}
希望这有帮助。
答案 5 :(得分:0)
您应该设置宽度,以便在HTML中使用它。
<div id="centerme">I'm a div and I wanna stay in the center!</div>
这适用于CSS。
#centerme{
position: fixed;
top:0;
bottom: 0;
left: 0;
right: 0;
margin: auto;
background:red;
width:250px;
height:60px;
}
PS:就像你可以看到你是否设置了高度,你也可以垂直居中;)(但你不需要它:))
答案 6 :(得分:0)
使用动态jquery代码将div放在中心
HTML:
<p><button id="button1">click and center the div</button></p>
<p class="centerDiv"></p>
Jquery的:
$("#button1").click(function(){
function movediv(){
win_width=$(window).width();
win_height=$(window).height();
div_width=$('.centerDiv').width();
div_height=$('.centerDiv').height();
$('.centerDiv').css('top',(win_height/2)-(div_height/2)).css('left',(win_width/2)-(div_width/2)).toggle();
}
movediv();
$(window).resize(function(){
movediv();
});
});
CSS:
.centerDiv{
background-color:red;
position:absolute;
width:200px;
height:100px;
}
<强> See Fiddle 强>