我想将一个 div 居中,但同时能够在我的代码中使用类似 top: 100px;
的内容。这可能吗?我注意到如果我说 position: fixed;
那么顶部/底部样式将起作用,但是 margin-left: auto
和 margin-right: auto
被禁用。我怎样才能同时获得这两个功能?谢谢!
最佳答案
根据您使用它的目的,最简单的方法可能是使用两个元素:一个具有固定位置的“不可见”元素和一个居中的内部元素。像这样:
<div>
<p>Test</p>
</div>
div {
position:fixed;
top:100px;
width:100%;
height:0; /* In case of z-index issues; this element should be "hidden" */
}
div p {
width:200px;
margin:0 auto;
background:#CCC;
}
关于html - 居中 div 并给它们顶部/底部定位?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9529072/