【发布时间】:2016-11-10 06:45:03
【问题描述】:
我正在尝试制作一个简单的解释页面,其中包含 3 个步骤以及示例代码块和简短描述。如果你去codepenhere,你会看到我在说什么(我也转载了下面的代码)。
共有 3 个步骤,每个步骤的 HTML/CSS 结构都是相同的。但是,它的某些内容可能会有所不同。如果你看一下代码笔,你会发现第一步和第三步看起来还不错。但是由于某种原因,代码块扩展到了不同的宽度。
- 这是第一个问题。如何让所有三个步骤的代码块(即
<div class="code">)长度相等?
第二个问题是即使我设置了overflow-x: scroll 和width: 100%,第2 步的代码块也会溢出到它的几个父div 之外。理想情况下,我希望代码块的宽度与其他两个相同,同时允许内部代码左右滚动。
- 这是第二个问题。如何约束 flexbox 中的 div,使其不会溢出其父级,同时允许在其直接父级 div 内滚动?
我希望我的解释是足够的。我很难描述这一点,因为我还不太熟悉 Flexbox 的怪癖。请看一下codepen,我相信它会变得更清晰。
提前致谢,请让我知道还有什么需要澄清的。
HTML:
<div class="container">
<div class="step">
<div class="number">1</div>
<div class="step-body">
<div class="description">This is a description of the terminal code block below:</div>
<div class="code"><pre>npm install foo bar</pre></div>
</div>
</div>
<div class="step">
<div class="number">2</div>
<div class="step-body">
<div class="description">This is a description of the very very very long single-line code block below:</div>
<div class="code"><pre>foo bar foo bar foo bar foo bar foo bar foo bar foo bar foo bar foo bar</pre></div>
</div>
</div>
<div class="step">
<div class="number">3</div>
<div class="step-body">
<div class="description">This is a description of the JSON code block below:</div>
<div class="code"><pre>{
"custom": {
"key": "a1b2c3d4e5f6"
}
}</pre></div>
</div>
</div>
</div>
CSS:
body {
display: flex;
justify-content: center;
align-items: center;
width: 100%;
height: 100%;
position: absolute;
}
.container {
max-width: 50%;
}
.step {
display: flex;
border: 1px solid red;
}
.number {
font-size: 2.5rem;
text-align: right;
flex-shrink: 0;
margin-right: 1rem;
width: 3rem;
}
.step-body {
padding-top: 1rem;
padding-bottom: 1rem;
}
.code {
background-color: black;
color: white;
width: 100%;
padding: 12px;
overflow-x: scroll;
}
【问题讨论】:
-
例如
overflow: scroll; width: 400px;对您有用吗?在 .code 类中。这是你想要的吗? -
@Apostolos 我感谢您的回复,但这对我不起作用,因为我无法硬设置宽度。我认为 flexbox 的全部意义在于我可以拥有流畅的布局(无需手动计算)。不幸的是,这行不通。
-
那么通过以百分比定义宽度,这三个块如何相等?我的意思是,这真的可以实现吗?很奇怪
-
@Apostolos 我只需要将块扩展到红色框的边缘。直观地说,
width: 100%应该可以工作,不是吗? -
这是您要找的吗? jsfiddle.net/0kqx79g9/8