我有一个div将有这个CSS:
#some_kind_of_popup
{
position: fixed;
top: 100px;
min-height: 300px;
width: 90%;
max-width: 900px;
}
Run Code Online (Sandbox Code Playgroud)
现在,我怎样才能使这个div居中?我可以使用margin-left: -450px; left: 50%;但这仅在屏幕> 900像素时才有效.之后(当窗口<900像素时),它将不再居中.
我当然可以用某种js来做这件事,但是用CSS做"更正确"吗?
lac*_*ass 205
您可以居中fixed或absolute定位的元素设置right和left到0,然后margin-left与margin-right以auto,如果你是一个中心static定位的元素.
#example {
position: fixed;
/* center the element */
right: 0;
left: 0;
margin-right: auto;
margin-left: auto;
/* give it dimensions */
min-height: 10em;
width: 90%;
}
Run Code Online (Sandbox Code Playgroud)
Ala*_*ows 48
如果您可以安全地使用CSS3的transform属性,这是另一种方法:
.fixed-horizontal-center
{
position: fixed;
top: 100px; /* or whatever top you need */
left: 50%;
width: auto;
-webkit-transform: translateX(-50%);
-moz-transform: translateX(-50%);
-ms-transform: translateX(-50%);
-o-transform: translateX(-50%);
transform: translateX(-50%);
}
Run Code Online (Sandbox Code Playgroud)
...或者如果你想要水平和垂直居中:
.fixed-center
{
position: fixed;
top: 50%;
left: 50%;
width: auto;
height: auto;
-webkit-transform: translate(-50%,-50%);
-moz-transform: translate(-50%,-50%);
-ms-transform: translate(-50%,-50%);
-o-transform: translate(-50%,-50%);
transform: translate(-50%,-50%);
}
Run Code Online (Sandbox Code Playgroud)
无论其内容的大小如何,这都有效
.centered {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
Run Code Online (Sandbox Code Playgroud)
来源:https://css-tricks.com/quick-css-trick-how-to-center-an-object-exactly-in-the-center/
<div id="container">
<div id="some_kind_of_popup">
center me
</div>
</div>
Run Code Online (Sandbox Code Playgroud)
你需要将它包装在一个容器中.这是css
#container{
position: fixed;
top: 100px;
width: 100%;
text-align: center;
}
#some_kind_of_popup{
display:inline-block;
width: 90%;
max-width: 900px;
min-height: 300px;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
129471 次 |
| 最近记录: |