One possibility is to separate the style of the markup in a CSS then to decide which <div>
color with what color.
div {
height: 100px;
width: 500px;
margin-bottom: 5px;
}
.gray {
background-color: gray;
}
.red {
background-color: red;
}
For this it is enough, with the help of ternary conditional operator, change the class of the element based on the function result in_array() returning true
if a value is contained in a specified array.
<!DOCTYPE html>
<html>
<head>
<title>DoWhile</title>
<meta charset="utf-8">
<!--link rel="stylesheet" href="{NOME DO ARQUIVO CSS}.css"-->
</head>
<body>
<?php
$indice = 0;
do {
?>
<div id="box" class="<?= in_array($indice,[2,6,10])? 'red': 'gray'; ?>">
<?= $indice;?>
</div>
<?php
$indice++;
}
while ($indice <= 12);
?>
</body>
</html>
Which results in:
div {
height: 100px;
width: 500px;
margin-bottom: 5px;
}
.gray {
background-color: gray;
}
.red {
background-color: red;
}
<!DOCTYPE html>
<html>
<head>
<title>DoWhile</title>
<meta charset="utf-8">
<!--link rel="stylesheet" href="{NOME DO ARQUIVO CSS}.css"-->
</head>
<body>
<div id="box" class="gray">
0
</div>
<div id="box" class="gray">
1
</div>
<div id="box" class="red">
2
</div>
<div id="box" class="gray">
3
</div>
<div id="box" class="gray">
4
</div>
<div id="box" class="gray">
5
</div>
<div id="box" class="red">
6
</div>
<div id="box" class="gray">
7
</div>
<div id="box" class="gray">
8
</div>
<div id="box" class="gray">
9
</div>
<div id="box" class="red">
10
</div>
<div id="box" class="gray">
11
</div>
<div id="box" class="gray">
12
</div>
</body>
</html>
Also as suggested in the comments it is possible to assign the class to be stylized only when the condition is met:
<!DOCTYPE html>
<html>
<head>
<title>DoWhile</title>
<meta charset="utf-8">
<!--link rel="stylesheet" href="{NOME DO ARQUIVO CSS}.css"-->
</head>
<body>
<?php
$indice = 0;
do {
?>
<div id="box" <?= in_array($indice,[2,6,10])? 'class="red"':''; ?>>
<?= $indice;?>
</div>
<?php
$indice++;
}
while ($indice <= 12);
?>
</body>
</html>
Resulting in:
div {
height: 100px;
width: 500px;
margin-bottom: 5px;
background-color: gray;
}
.red {
background-color: red;
}
<!DOCTYPE html>
<html>
<head>
<title>DoWhile</title>
<meta charset="utf-8">
<!--link rel="stylesheet" href="{NOME DO ARQUIVO CSS}.css"-->
</head>
<body>
<div id="box">
0
</div>
<div id="box">
1
</div>
<div id="box" class="red">
2
</div>
<div id="box">
3
</div>
<div id="box">
4
</div>
<div id="box">
5
</div>
<div id="box" class="red">
6
</div>
<div id="box">
7
</div>
<div id="box">
8
</div>
<div id="box">
9
</div>
<div id="box" class="red">
10
</div>
<div id="box">
11
</div>
<div id="box">
12
</div>
</body>
</html>
One suggestion in this form would be to remove the class
.gray
and add to the standard class stylediv
, applying only the alternative classes when they are triggered.– Weslley Araújo
@Weslleyaraújo, the guidelines have been incorporated the reply. Thank you.
– Augusto Vasques