如何使用flexbox在容器中水平和垂直居中div.在下面的例子中,我希望每个数字彼此相同(在行中),它们是水平居中的.
.flex-container {
padding: 0;
margin: 0;
list-style: none;
display: flex;
align-items: center;
justify-content: center;
}
row {
width: 100%;
}
.flex-item {
background: tomato;
padding: 5px;
width: 200px;
height: 150px;
margin: 10px;
line-height: 150px;
color: white;
font-weight: bold;
font-size: 3em;
text-align: center;
}Run Code Online (Sandbox Code Playgroud)
<div class="flex-container">
<div class="row">
<span class="flex-item">1</span>
</div>
<div class="row">
<span class="flex-item">2</span>
</div>
<div class="row">
<span class="flex-item">3</span>
</div>
<div class="row">
<span class="flex-item">4</span>
</div>
</div>Run Code Online (Sandbox Code Playgroud)
因此,在尝试使用flexbox创建一个有用的模式时,我发现了什么似乎是一个浏览器问题,我想知道是否有一个已知的修复或解决方法 - 或者如何解决它的想法.
我想解决的问题有两个方面.首先,使模态窗口垂直居中,这可以按预期工作.第二个是让模态窗口滚动 - 外部,所以整个模态窗口滚动,而不是其中的内容(这样你就可以有下拉列表和其他可以扩展到模态边界之外的UI元素 - 像自定义日期选择器等)
但是,当将垂直居中与滚动条组合时,模态的顶部在开始溢出时可能无法进入.在上面的示例中,您可以调整大小以强制溢出,这样做可以让您滚动到模态的底部,但不能滚动到顶部(第一段被截断).
这是示例代码的链接(高度简化)
https://jsfiddle.net/dh9k18k0/2/
.modal-container {
position: fixed;
top: 0;
left: 0;
bottom: 0;
right: 0;
background: rgba(0, 0, 0, 0.5);
overflow-x: auto;
}
.modal-container .modal-window {
display: -ms-flexbox;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
// Optional support to confirm scroll behavior makes sense in IE10
//-ms-flex-direction: column;
//-ms-flex-align: center;
//-ms-flex-pack: center;
height: 100%;
}
.modal-container .modal-window .modal-content {
border: 1px solid #ccc;
border-radius: 4px;
background: #fff;
width: 100%;
max-width: 500px; …Run Code Online (Sandbox Code Playgroud) 我尝试使用flexbox方法,表格方法和其他一些方法垂直居中一个未知高度的div,但我的div没有正确居中.我希望居中div的宽度为窗口宽度的50%或最小宽度为200px.
.content {
background-color: violet;
min-width: 200px;
width: 50%;
margin-left: auto;
margin-right: auto;
box-shadow: 0px 1px 7px 1px rgba(0, 0, 0, 1);
}
.outer-container {
display: table;
width: 100%;
background-color: violet;
}
.container {
display: table-cell;
text-align: center;
vertical-align: middle;
}Run Code Online (Sandbox Code Playgroud)
<body>
<div class="outer-container">
<div class="container">
<div class="content">
<div class="title-class">
Hello there
</div>
</div>
</div>
</div>
</body>Run Code Online (Sandbox Code Playgroud)