Home > Software design >  How to apply padding in parent div that doesn't apply on one child
How to apply padding in parent div that doesn't apply on one child

Time:12-06

This is what I want to achieve

enter image description here

The white background is parent div, I want to apply some padding on left, right and top, but in such a way that it is not applied on the last child div. How to achieve this with CSS ? Adding padding directly applies it to all the children, Is there a way to revert this for a particular child ?

JSX Structure:

<div className="parent">
  <div className="child-1"></div>
  <div className="child-2"></div>
  <div className="child-3"></div>
</div>

I have arranged the children divs, but not able to figure out how to apply padding for required condition ?
Is applying margin on individual children the only possible way ? (I want to keep this as last option as number of children may increase or change dynamically, so it will become unmaintainable.

CodePudding user response:

Use :last-child selector

.parent {
  background: magenta;
  display: flex;
  flex-direction: column;
}

.parent > * {
  height: 100px;
  background: green;
  margin: 10px;
}

.parent :last-child {
  margin: 0;
  background: blue;
}
<div >
  <div ></div>
  <div ></div>
  <div ></div>
</div>

CodePudding user response:

Another option is to use margin on the first 2 children,

and no padding on the parent.

  • Related