css没有编辑周围的HTML

时间:2017-02-01 08:27:11

标签: html css

问题是使用css来定位和着色文章。

Question description screenshot here

提供的原始代码:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Articles</title>
  <style>
    /* Write your CSS solution here (do not edit the surrounding HTML) */
  </style>
</head>
<body>
  <article>First</article>
  <article>Second</article>
  <article>Third</article>
  <article>Fourth</article>
</body>
</html>

是否真的有可能在不区分这四个文章标签的情况下解决问题?我想出的唯一解决方案是添加“class”属性和位置&amp;相应地着色每个,但这违反了我们无法编辑周围HTML的规则。

提前致谢!

5 个答案:

答案 0 :(得分:2)

如果您无法编辑html,可以使用nth-child选择器,如下所示:

body article:nth-child(1){background: red;}
body article:nth-child(2){background: blue;}
body article:nth-child(3){background: green;}
body article:nth-child(4){background: orange;}

body article{float: left; width:50%; padding-bottom: 50px;}

https://jsfiddle.net/Lczrmb0k/2/

答案 1 :(得分:0)

是的,您可以使用nth-child属性,并通过相对于父级的位置来引用每篇文章。含义:

如果要将红色设置为第一篇文章,则规则应为:

article:nth-child(1){color:red}

对于第二个兄弟姐妹:

article:nth-child(2){color:blue}

它们都可以用数字引用:)

你甚至可以在不编辑HTML的情况下做更多疯狂的事情,看看this article

答案 2 :(得分:0)

这是一个解决方案:

&#13;
&#13;
html, body{
    width: 100%;
    height: 100%;
    margin: 0;
    padding: 0;
}
article {
    display: inline-block;
    box-sizing: border-box;
    width: 50%;
    height: 50%;
    float: left;
}
article:nth-child(1) {
    background: red;
}
article:nth-child(2) {
    background: orange;
}
article:nth-child(3) {
    background: tomato;
}
article:nth-child(4) {
    background: teal;
}
&#13;
<article>First</article>
  <article>Second</article>
  <article>Third</article>
  <article>Fourth</article>
&#13;
&#13;
&#13;

答案 3 :(得分:0)

您可以使用:nth-child

&#13;
&#13;
article:nth-child(2n){
  background-color: red;  
}
article:nth-child(2n+1){
  background-color: yellow;  
}
article:nth-child(3n){
  background-color: lightblue;  
}
article:nth-child(4n+3){
  background-color: lightgreen;  
}
&#13;
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Articles</title>
  <style>
    /* Write your CSS solution here (do not edit the surrounding HTML) */
  </style>
</head>
<body>
  <article>First</article>
  <article>Second</article>
  <article>Third</article>
  <article>Fourth</article>
</body>
</html>
&#13;
&#13;
&#13;

答案 4 :(得分:0)

你应该使用 nth-child css 函数。

body {
  margin: 0px;
}

article {
  width: 50%;
  float: left;
  height: 50vh;
}

article:nth-child(1) {
  background: red;
}

article:nth-child(2) {
  background: yellow;
}

article:nth-child(3) {
  background: blue;
}

article:nth-child(4) {
  background: green;
}
<head>
  <meta charset="utf-8">
  <title>Articles</title>
</head>

<body>
  <article>First</article>
  <article>Second</article>
  <article>Third</article>
  <article>Fourth</article>
</body>