回答(12)
2 years ago
简单的方法,如果你有一个固定的宽度和高度:
#divElement{
position: absolute;
top: 50%;
left: 50%;
margin-top: -50px;
margin-left: -50px;
width: 100px;
height: 100px;
}
2 years ago
随着变形越来越受到支持,你可以在不知道弹出窗口的宽度/高度的情况下做到这一点
.popup {
position: fixed;
top: 50%;
left: 50%;
-webkit-transform: translate(-50%, -50%);
transform: translate(-50%, -50%);
}
Update: 查看https://css-tricks.com/centering-css-complete-guide/以获得有关CSS居中的详尽指南 . 将它添加到这个答案,因为它似乎得到了很多的关注 .
2 years ago
设置宽度和高度,你很好 .
div {
position: absolute;
margin: auto;
top: 0;
right: 0;
bottom: 0;
left: 0;
width: 200px;
height: 200px;
}
如果您希望元素维度具有灵活性(并且不关心旧版浏览器),请使用 XwipeoutX 的答案 .
2 years ago
现在,使用HTML 5和CSS 3更容易:
TODO supply a titlebody > div {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
display: flex;
justify-content: space-around;
align-items: center;
flex-wrap: wrap;
}
2 years ago
如果你有一个固定的 div 绝对位置,它从顶部开始为50%,左边为50%,负边距分别为高度和宽度的一半左右 . 根据您的需求调整:
div {
position: absolute;
top: 50%;
left: 50%;
width: 500px;
height: 300px;
margin-left: -250px;
margin-top: -150px;
}
2 years ago
它适用于任何对象 . 即使你不知道大小:
.centered {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
2 years ago
使用flex . 更简单,无论你的 div 尺寸如何都会有效:
.center-screen {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
text-align: center;
min-height: 100vh;
}
I'm in the center
2 years ago
试试这个:
width:360px;
height:360px;
top: 50%; left: 50%;
margin-top: -160px; /* ( ( width / 2 ) * -1 ) */
margin-left: -160px; /* ( ( height / 2 ) * -1 ) */
position:absolute;
2 years ago
如果有人在寻找解决方案,
我找到了这个,
它是我发现的最佳解决方案!
div {
width: 100px;
height: 100px;
background-color: red;
position: absolute;
top:0;
bottom: 0;
left: 0;
right: 0;
margin: auto;
}
希望你喜欢!
2 years ago
另一种在中心显示块的简单灵活方法:使用 line-height 和 text-align 的原生文本对齐 .
解:
.parent {
line-height: 100vh;
text-align: center;
}
.child {
display: inline-block;
vertical-align: middle;
line-height: 100%;
}
和HTML示例:
我们使 div.parent 全屏,并且他的单个孩子 div.child 与 display: inline-block 对齐为文本 .
好处:
灵活性,没有绝对值
支持调整大小
在手机上运行正常
2 years ago
我会在CSS中这样做:
div.centered {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
然后在HTML中:
2 years ago
试试这个
Your Html code Here |
或这个
Your Html code here