Reputation: 3
I'm relatively new to CSS. I have a very simple setup: a main parent element with three child elements. I want to all child elements to have the same padding but in their own color. Right now, I'm doing the following (just as an example):
.parent {
padding-top: 20px;
background-color: white;
}
.child1 {
background-color: gray;
}
.child2 {
background-color: red;
}
.child3 {
background-color: inherit;
}
The background color is set for each child just fine, but the padding retains the color of the parent. I was wondering if there is anyway for the child elements to each have their own padding color without having to add 'padding-top' for each.
Here is the HTML snippet:
<!DOCTYPE html>
<html>
<head>
<title>Amazing</title>
<link rel="stylesheet" href="css/main.css">
</head>
<body>
<div class="parent">
<div class="child1">
<h1> Child1 </h1>
</div>
<div class="child2">
<h1> Child2 </h1>
</div>
<div class="child3">
<h1> Child3 </h1>
</div>
</div>
</body>
</html>
Upvotes: 0
Views: 871
Reputation: 53674
If you want the children to have their own padding, you'll need to apply padding to them all... but you don't have to write out out for each element. You can group the styles using a common class (like .child
) or the .parent > *
selector to select all direct children of .parent
. I used the class .parent-all
for this demo just to differentiate the groups to show both of these methods.
.parent {
background-color: white;
}
.child1 {
background-color: gray;
}
.child2 {
background-color: red;
}
.child3 {
background-color: inherit;
}
.parent-all > * {
padding-top: 20px;
}
.parent .child {
padding-top: 20px;
}
<div class="parent parent-all">
<div class="child1">child1</div>
<div class="child2">child2</div>
<div class="child3">child3</div>
</div>
<div class="parent">
<div class="child child1">child1</div>
<div class="child child2">child2</div>
<div class="child child3">child3</div>
</div>
Upvotes: 1