所以我在这里使用这种样式将 div 作为背景居中:
#example{
z-index:-1;
width: 950px;
height:100%;
position:fixed;
background-color:#F0F0F0;
background:url(images/main_background_sidebar.png) repeat-y top center;
top: 0px;
left: 50%;
margin-left: -475px;
}
效果很好,它保持居中,但如果页面宽度小于 950 像素,是否有办法阻止它保持居中?例如:如果浏览器窗口只有 800px 宽,则背景图像的左侧会粘在屏幕的左侧。
最佳答案
如果您可以使用 CSS3,那么您可以申请 @media
规则。一个未经测试的可能性:
#example {
/* Don't center it. */
}
@media only screen and (min-width: 950px) and (min-device-width: 950px) {
#example {
/* It's 950px or more! Let's center it! */
}
}
只需阅读并使用它即可。
更新:我该如何使用它?我应该把它放在哪里,就在我的 style.css
中?
Media queries can be used in tags, XML processing instructions, the @import at-rule, and the @media at-rule.
关于javascript - 如果页面大于 div,则仅居中 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11066526/