缩小与浮动元素共享空间的 HTML 元素的边框

问题描述 投票:0回答:1

当浮动元素占用一些空间时,“普通”文本会腾出空间来容纳浮动元素。但普通文本周围的边框不会,而是与浮动元素相交。

在下面的示例中,如何使第一个红色框在蓝色框开始之前结束并有一些间隙,并且不重叠?并且让第二个不需要与浮动元素共享空间的红框仍然占据100%?

div#toc {
  float: right;
  width: 300px;
  padding: 20px;
  border: 1px solid blue;
}

div.warn {
  padding: 20px;
  border: 1px solid red;
}
<div id="toc">
  <h2>Table of contents</h2>
  <ol>
    <li>Chapter 1</li>
    <li>Chapter 2</li>
    <li>Chapter 3</li>
  </ol>
</div>
<div id="main">
  <h1>Chapter 1</h1>
  <p>In the beginning ...</p>
  <div class="warn">
    Fairy tale, watch out!
  </div>
  <p>... and were married happily ever after.</p>
  <div class="warn">
    Don't retell!
  </div>
</div>

html css
1个回答
0
投票

不要使用

<div>
中的裸文本,而是坚持使用语义标记并继续使用
<p>
来表示文本。我们需要做的就是更新 CSS
.warn
类以将警告显示为内联块:

#toc {
  float: right;
  width: 300px;
  padding: 20px;
  border: 1px solid blue;
  clear: both;
}

.warn {
  display: inline-block;
  padding: 20px;
  border: 1px solid red;
}
<div id="toc">
  <h2>Table of contents</h2>
  <ol>
    <li>Chapter 1</li>
    <li>Chapter 2</li>
    <li>Chapter 3</li>
  </ol>
</div>

<div id="main">
  <h1>Chapter 1</h1>
  <p>In the beginning ...</p>

  <p class="warn">
    Fairy tale, watch out!
  </p>

  <p>... and were married happily ever after.</p>

  <p class="warn">Don't retell!</p>
</div>

© www.soinside.com 2019 - 2024. All rights reserved.