我有一个布局,其中有 3 列。
因此,我将 100% 除以 3。
结果显然是33.333....
我的目标是完美的 1/3 屏幕。
问题:
CSS 可以处理点后多少个数字来指定宽度的 1/3?
例如33.33333
(n=5)
← css 可以处理多少个 n
HTML:
<div id="wrapper">
<div id="c1"></div>
<div id="c2"></div>
<div id="c3"></div>
</div>
CSS:
#c1, #c2, #c3 {
width: 33%; // 1/3 of 100%
}
除以 3 有更好的方法吗?
最佳答案
现在是 2018 年,请使用 flexbox - 不再有 inline-block
whitespace 问题:
body {
margin: 0;
}
#wrapper {
display: flex;
height: 200px;
}
#wrapper > div {
flex-grow: 1;
}
#wrapper > div:first-of-type { background-color: red }
#wrapper > div:nth-of-type(2) { background-color: blue }
#wrapper > div:nth-of-type(3) { background-color: green }
<div id="wrapper">
<div id="c1"></div>
<div id="c2"></div>
<div id="c3"></div>
</div>
甚至CSS grid如果您要创建网格。
body {
margin: 0;
}
#wrapper {
display: grid;
grid-template-columns: repeat(3, 1fr);
grid-auto-rows: minmax(200px, auto);
}
#wrapper>div:first-of-type { background-color: red }
#wrapper>div:nth-of-type(2) { background-color: blue }
#wrapper>div:nth-of-type(3) { background-color: green }
<div id="wrapper">
<div id="c1"></div>
<div id="c2"></div>
<div id="c3"></div>
</div>
使用 CSS calc()
:
body {
margin: 0;
}
div {
height: 200px;
width: 33.33%; /* as @passatgt mentioned in the comment, for the older browsers fallback */
width: calc(100% / 3);
display: inline-block;
}
div:first-of-type { background-color: red }
div:nth-of-type(2) { background-color: blue }
div:nth-of-type(3) { background-color: green }
<div></div><div></div><div></div>
引用资料:
关于html - css 分割宽度 100% 到 3 列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18781713/