Pull the previous sibling element

You can use margin-right, for example, to push a next sibling as seen below:

CSS:

#parent {
  background: tan;
  font-size: 0;
}

#parent * {
  display: inline-block;
  width: 50px;
  height: 50px;
}

#child1 {
  background: teal;
  margin-right: 100px;
}

#child2 {
  background: olive;
}

HTML:

<div id="parent">
  <div id="child1"></div>
  <div id="child2"></div>
</div>

DEMO

I know there is no previous sibling selector in CSS. However, I wonder if there’s a workaround so #child2 can pull #child1 to a distance of say, 20px. Here’s a before-after screenshot:

Note: I don’t want to give a margin value to #child1 or alter the HTML. The effect should be achieved using #child2 only.

Does this do what you want?

#child2 {
  background: olive;
  float:left;
  margin-left:20px;
  margin-right:80px;
}

Thanks for the answer, but the result isn’t similar to the screenshot: the olive box should be on the right.

Oh yes:)

Try this:

#child2 {
  background: olive;
  float:left;
  margin-left:150px;
  margin-right:-180px;
}
3 Likes

You’re one of a kind, Paul! Thanks! :slight_smile:

2 Likes

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.