折叠屏幕边缘的边距

时间:2018-05-20 05:26:36

标签: html css margin

我正在尝试创建一个响应式布局,根据需要在小屏幕上将一个部分中的项目折叠成多行。当前行为有效,但无法利用所有水平空间。如果某个项目是其最后一个项目,我该如何禁用右边距?



span {
 white-space: nowrap;
 display: inline-block;
 margin-bottom: 1em;
 margin-right: 10em;
}

<h1>Section 1</h1>
<span>Item 1</span>
<span>Item 2</span>
<h1>Section 2</h1>
<span>Item 1</span>
<span>Item 2</span>
<span>Item 3</span>
<span>Item 4</span>
<h1>Section 3</h1>
<span>Item 1</span>
<span>Item 2</span>
<span>Item 3</span>
<span>Item 4</span>
<span>Item 5</span>
<span>Item 6</span>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:0)

如果可以更改html,可以试试这个:

<section>
  <h1>Section 1</h1>
  <span>Item 1</span>
  <span>Item 2</span>
</section>
<section>
  <h1>Section 2</h1>
  <span>Item 1</span>
  <span>Item 2</span>
  <span>Item 3</span>
  <span>Item 4</span>
</section>
<section>
  <h1>Section 3</h1>
  <span>Item 1</span>
  <span>Item 2</span>
  <span>Item 3</span>
  <span>Item 4</span>
  <span>Item 5</span>
  <span>Item 6</span>
</section>

并使用css伪选择器:类似于last-of-type:

span {
  white-space: nowrap;
  display: inline-block;
  margin-bottom: 1em;
  margin-right: 10em;
}
span:last-of-type {
  margin-right: 0;
}

了解详情:https://developer.mozilla.org/en-US/docs/Web/CSS/:last-of-type

答案 1 :(得分:0)

一种可能的解决方案是使用section将每个块包装在overflow: hidden标记中。然后将项目包装在宽度等于100%+一个边距右的div中,如下所示:width: calc(100% + 10em);

以下是完整示例:

&#13;
&#13;
section {
  border: 1px dashed coral;
  overflow: hidden;
}

.items {
  border: 1px solid green;
  width: calc(100% + 10em);
}

span {
 white-space: nowrap;
 display: inline-block;
 margin-bottom: 1em;
 margin-right: 10em;
 
 border:1px solid pink;
}
&#13;
<section>
  <h1>Section 1</h1>
  
  <div class="items">
    <span>Item 1</span>
    <span>Item 2</span>  
  </div>
</section>

<section>
  <h1>Section 2</h1>
  
  <div class="items">
    <span>Item 1</span>
    <span>Item 2</span>
    <span>Item 3</span>
    <span>Item 4</span>
  </div>
</section>

<section>
  <h1>Section 3</h1>
  
  <div class="items">
    <span>Item 1</span>
    <span>Item 2</span>
    <span>Item 3</span>
    <span>Item 4</span>
    <span>Item 5</span>
    <span>Item 6</span>
  </div>
</section>
&#13;
&#13;
&#13;