在我做了一些更改后,我的反馈div不再以屏幕为中心,我无法弄清楚原因.
要使元素居中,只需设置宽度然后就可以了margin: 0 auto; 这应该足够了.
目标是让div显示在屏幕顶部,居中.你可以在这里看到我的fiddel:
码:
#feedback {
position: fixed;
top: 0px;
min-height: 50px;
width: 300px;
margin: 10px auto;
z-index: 9000;
font-weight: bold;
line-height: 24px;
border: solid 1px #d1d2d1;
padding: 10px;
background-color: #f7f2e7;
display: none;
border-radius: 5px;
-moz-border-radius: 5px; /* FF < 4.0 */
-webkit-border-radius: 5px; /* Rounded corners for Safari */
}
#feedback span { display: block; float: left;}
#feedback #feedback_icon { width: 24px; height: 24px; overflow: hidden; margin-right: 10px; }
#feedback #feedback_text { height: 24px; line-height: 24px; display: inline-block; }
?
<div class="clearfix" id="feedback" style="display: block;"><span class="dialogFail" id="feedback_icon"></span><div class="" id="feedback_text">Message here</div></div>
Run Code Online (Sandbox Code Playgroud)
任何帮助赞赏!
auto边距不适用于元素position: fixed.
相反,你需要这样做:
left: 50%;
margin-left: -Xpx;
width: Ypx;
box-sizing: border-box;
Run Code Online (Sandbox Code Playgroud)
哪里X = Y/2.
(box-sizing: border-box确保即使你有填充或边框,它仍然会居中.如果这会干扰所需的宽度,然后将其删除并padding-left + border-left-width从中减去margin-left.)