html - css 分割宽度 100% 到 3 列

标签 html css

我有一个布局,其中有 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>

JSFiddle


引用资料:

关于html - css 分割宽度 100% 到 3 列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18781713/

相关文章:

html - 使用 *ngFor [ngStyle] 更改所有背景颜色

css - 另一个带有 "white-space: nowrap;"的 div 的背景不覆盖所有宽度

css - ionic 标签未正确与其组对齐

jquery - FlexSlider 2 - 无法制作全宽、左右空白

php - 为什么我的 .php 网页背景颜色没有改变,即使我改变了 CSS 样式表中的背景颜色属性?

html - css 如何使元素边距底部转到其容器的底部

javascript - 更改标题属性的字体系列

javascript - 如何停止 2 个按钮做同样的工作?在这种情况下,它们都滚动到顶部

css - 如何使溢出元素不增加 flexbox 的高度?

html - 使用bootstrap可变高度堆叠的两列元素