居中被滚动条宽度抛出
我试图用flexbox将两个<div>
的内容居中。 我看了下面的线程:滚动flex容器不适合中心项目
<div>
的内容是固定宽度的表格,我将flex-grow设置为none。 问题是第二个div的滚动条所占用的空间在对齐时也会被考虑。
这里有个简单的例子:http://jsfiddle.net/boc39Lsa/2/
#container {
background-color: green;
display: flex;
/*overflow: auto;*/
}
.item {
background-color: white;
border: 1px solid black;
flex-grow: 0;
}
.item:first-child {
margin-left: auto;
}
.item:last-child {
margin-right:auto;
}
.bigContent{
height: 1000px;
}
.scroll{
overflow: auto;
height: 300px;
}
<div id="container">
<div class="item">
<table width="500px">
<tr><td>Header</td></tr>
</table>
</div>
</div>
<div id="container">
<div class="item scroll">
<div class="bigContent">
<table width="500px">
<tr><td>Some content</td></tr>
</table>
</div>
</div>
</div>
由于滚动条添加到元素的宽度,并且由于滚动条的宽度在浏览器之间有所不同,因此不存在用于避免此行为的直接属性。
我想到的最简单的解决方案是使用500px的初始flex-basis
,并将table
设置为100%宽
堆栈片段
#container {
background-color: green;
display: flex;
}
.item {
background-color: white;
border: 1px solid black;
flex-basis: 500px;
}
.item:first-child {
margin-left: auto;
}
.item:last-child {
margin-right:auto;
}
.bigContent{
height: 1000px;
}
.scroll{
overflow-y: auto;
overflow-x: hidden;
height: 300px;
}
<div id="container">
<div class="item">
<table width="100%">
<tr><td>Header</td></tr>
</table>
</div>
</div>
<div id="container">
<div class="item scroll">
<div class="bigContent">
<table width="100%">
<tr><td>Some content</td></tr>
</table>
</div>
</div>
</div>
要在中心制作内容,只需将容器内部的对齐设置为居中,如
text-align: center;
#container {
background-color: green;
display: flex;
text-align: center;
/*overflow: auto;*/
}
.item {
background-color: white;
border: 1px solid black;
flex-grow: 0;
}
.item:first-child {
margin-left: auto;
}
.item:last-child {
margin-right:auto;
}
.bigContent{
height: 1000px;
}
.scroll{
overflow: auto;
height: 300px;
}
<div id="container">
<div class="item">
<table width="500px">
<tr><td>Header</td></tr>
</table>
</div>
</div>
<div id="container">
<div class="item scroll">
<div class="bigContent">
<table width="500px">
<tr><td>Some content</td></tr>
</table>
</div>
</div>
</div>
链接地址: http://www.djcxy.com/p/76041.html