[英]Horizontally center a div with a fixed position
在以下代码中,如何将div以固定位置水平居中? 我已经尝试了几件事,但是没人能正确地做到这一点。
我正在尝试使div从顶部起100像素,并水平居中。
<!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);
}
示例代码: http : //codepen.io/anon/pen/fqpwd
如果div具有特定宽度,请尝试添加以下内容:
width: somevalue;
left: 50%;
margin-left: -somevalue/2;
参见示例: http : //jsfiddle.net/NZX38/
如果您将其宽度固定为任意值(可以是百分比),则可以这样操作:
width: 250px;
position: fixed;
left: 50%;
margin-left: -125px; /* 250 / 2 */
如果使用百分比,则更简单:
width: 50%;
position: fixed;
left: 25%; /* (100 - width) / 2 */
工作提琴: JSFiddle
干得好。
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);
}
希望这可以帮助。
您应该设置宽度,以便可以在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:就像您可以看到是否设置了高度一样,也可以将其垂直居中;)(但不需要它:))
使用动态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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.