user7596377
user7596377

Reputation:

Positioned 3 different divs

I have 3 different divs in html file.

div {
  width: 200px;
  height: 200px;
  position: absolute;
}

.second {
  background: red;
  left: 200px;
  top: 200px;
}

.third {
  background: green;
  top: 400px;
  left: 400px;
}

.first {
  background: yellow;
}
<div class="first"></div>
<div class="second"></div>
<div class="third"></div>

I want to move one div.Anyone I want.But when I move any divs this must effect others.Example:When I added margin to .second div this divs change position in page flow.I want this effects to .first and .third div.How can I do it?

Expected output:

expected output

Upvotes: 0

Views: 75

Answers (3)

Ethan
Ethan

Reputation: 446

If I understand this correctly, you want to add a margin on all three divs?

We can do that by putting them inside a container.

<div class="container">
  <div class="first"></div>
  <div class="second"></div>
  <div class="third"></div>
</div>

And adding the margin to the container class.

.container {
  margin: 10px
}

Working JSFiddle: https://jsfiddle.net/pcyq20vx/

Upvotes: 0

amansoni211
amansoni211

Reputation: 929

Instead of position: absolute let it be relative

Have a look at the CodePen Example if this solves your problem

div {
  width: 200px;
  height: 200px;
  /*   position: absolute; */
}

.second {
  background: red;
  margin-left: 200px;
}

.third {
  background: green;
  margin-left: 400px;
}

.first {
  background: yellow;
}

HTML:

<div class="first"></div>
<div class="second"></div>
<div class="third"></div>

Upvotes: 0

Briley Hooper
Briley Hooper

Reputation: 1271

The purpose of CSS position:absolute is to remove the element from the document flow so that changing the margins or size won't effect other elements around it.

If you want your <div>s to be affected by margins of other divs, instead of using position:absolute try using float:left (or flexbox for a more powerful solution).

Upvotes: 1

Related Questions