如何只将一个div的某些元素放在一个css框中

时间:2014-08-30 10:42:40

标签: html css css-selectors

我正在参加CSSzenGarden挑战赛。我必须在不改变它的情况下设置html样式。我试图将这些段落放在一个盒子里,而不是将h3放在那个盒子里面。我希望h3位于包含段落的方框之上。

    <div class="preamble" id="zen-preamble" role="article">
        <h3>The Road to Enlightenment</h3>
        <p>Littering a dark and dreary road lay the past relics of browser-specific tags, incompatible <abbr title="Document Object Model">DOM</abbr>s, broken <abbr title="Cascading Style Sheets">CSS</abbr> support, and abandoned browsers.</p>
        <p>We must clear the mind of the past. Web enlightenment has been achieved thanks to the tireless efforts of folk like the <abbr title="World Wide Web Consortium">W3C</abbr>, <abbr title="Web Standards Project">WaSP</abbr>, and the major browser creators.</p>
        <p>The CSS Zen Garden invites you to relax and meditate on the important lessons of the masters. Begin to see with clarity. Learn to use the time-honored techniques in new and invigorating fashion. Become one with the web.</p>
    </div>

当我使用.preamble作为css选择器时,它将整个div放在框内。当我使用.preamble p作为选择器时,它会将每个段落放在一个单独的框中。

如何在不包含h3的情况下选择所有段落作为一个组?

3 个答案:

答案 0 :(得分:3)

使用带有正值和负值的margin-top

.preamble {
    border: 1px solid black;
    margin-top: 20px
}
.preamble h3 {
    margin: -20px 0px;
}

http://jsfiddle.net/3ez4qh3m/

对于特定的选择器:你不能这样做。您既可以选择整个容器.preamble,也可以选择单个元素.preamble p.preamble h3,但在排除子容器时不能选择容器。

答案 1 :(得分:0)

您可以选择p元素中的所有div.preamble元素,如下所示:

div.preamble > p {
    /* some nice styling goes here */
}

这将选择div.preable元素的所有直接子元素作为段落元素。

您还可以选择某种类型的所有孩子(不一定是直接的),如下所示:

div.preamble * {
    /* even more nice styling goes here */
}

您可以用您喜欢的任何元素替换星号,或将其保留在那里并选择div.preamble的所有孩子。我希望这可以解决问题,祝你好运!


我刚注意到我没有完全回答你的问题。你不能制作一个盒子&#39;在段落周围,因为一个框并不真正意味着任何东西,除了可能将你的段落包含在一个实际元素中,如div。但是,您可以为所有段落提供相同的背景颜色:

div.preamble > p {
    background-color: red;
}

或在它们周围放置边框:

/* put a border around all paragraphs and remove their margin */
div.preamble > p {
    margin: 0;
    border: 1px solid green;
}

/* remove the bottom margin of the first and second paragraph 
 * (remember that they are preceded by a heading element, so the 
 * first paragraph is the second child) */
div.preamble > p:nth-child(2), div.preamble > p:nth-child(3) {
    border-bottom: none;
}

/* remove the top margin of the second and third paragraph */
div.preamble > p:nth-child(3), div.preamble > p:nth-child(4) {
    border-top: none;
}

我认为这就像你制作一盒你的段落一样接近。祝你好运。

答案 2 :(得分:0)

这个答案是你完成后的额外可能性。

此处的表格布局非常有用,并且会将所有内容保留在文档的常规流程中: DEMO

基本CSS:

.preamble {
  display:table;
  width:100%;
  table-layout:fixed;
  background:/* whatever */;
  border:double; /* whatever, optionnal */
}
.preamble h3 {
  display:table-caption;
  background:/* whatever */;
  text-align:center;/* whatever, optionnal */
  margin:1em 0;/* whatever, optionnal */
}

<edit data-why="any feed back ?"/>

get this h3 outside