CSS 由于绝对位置,如何使Modal位于屏幕中央?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38675321/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to make Modal in the center of screen due to absolute position?
提问by Toby
I created a Modal for my framework. I created everything like HTML Codes, CSS Codes & JS Codes ..., It works very good !
我为我的框架创建了一个模态。我创建了 HTML 代码、CSS 代码和 JS 代码之类的一切,效果非常好!
My only problem is that I can't make it CENTER & RESPONSIVE ... This is my CSS Codes for Modal Div :
我唯一的问题是我不能让它成为 CENTER & RESPONSIVE ...这是我的 Modal Div 的 CSS 代码:
.ji-modal {
width: 700px;
height: auto;
background-color: #FFF;
border: 1px solid #CCC;
position: fixed;
top: 70px;
left: 325px;
display: none;
z-index: 1000005;
}
I have read that If your width is fixed & your tag has a Absolute or Fixed Position, You can make it center by giving 50% to left ro right, But It doesn't work too ...
我读过如果您的宽度是固定的并且您的标签具有绝对或固定位置,您可以通过给左 ro 右 50% 使其居中,但它也不起作用......
Any Help, Thanks ...
任何帮助,谢谢...
采纳答案by Oskar
To make it responsive, instead try setting the width
using %
or vw
units. Also, to center it horizontally you can use margin: 0 auto
. Centering it vertically is a little more tricky, check out this answerfor more on that.
要使其具有响应性,请尝试设置width
使用%
或vw
单位。此外,要水平居中,您可以使用margin: 0 auto
. 将其垂直居中有点棘手,请查看此答案以了解更多信息。
回答by Toby
Setting sizes in percentages is a good option, another option is to use transform
:
以百分比为单位设置大小是一个不错的选择,另一种选择是使用transform
:
.modal {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
This will move the modal to 50% from top and left, and then adjust it back based upon the dimensions of the modal itself. This isn't ideal for every situation, but it works well in many modal use cases.
这会将模态从顶部和左侧移动到 50%,然后根据模态本身的尺寸将其调整回来。这并不适用于所有情况,但它在许多模态用例中运行良好。
回答by christianAV
Did you tried this:
你有没有试过这个:
.modal-content{
position: relative;
display: flex;
flex-direction: column;
margin-top: 50%;
}