5.5: Absolute

An absolute: element is

  • is isolated from the normal flow and other elements

  • BUT will respond to other positional properties and values.

Copy and paste the following.

<figure class="box-1"></figure>
<figure class="box-2"></figure>
<figure class="box-3"></figure>
<figure class="box-4"></figure>
body {
  background: #eee;
}

.box-1 {
  position: absolute;
  width: 250px;
  height: 250px;
  background: pink;
  top: 50%;
  left: 50%;
  margin-top: -125px;
  margin-left: -125px;
}

.box-2 {
  position: absolute;
  width: 200px;
  height: 200px;
  background: rgba(199,21,133,1.0);
  top: 50%;
  left: 50%;
  margin-top: -100px;
  margin-left: -100px;
}

.box-3 {
  position: absolute;
  width: 150px;
  height: 150px;
  background: pink;
  top: 50%;
  left: 50%;
  margin-top: -75px;
  margin-left: -75px;
}

.box-4 {
  position: absolute;
  width: 100px;
  height: 100px;
  background: rgba(199,21,133,1.0);
  top: 50%;
  left: 50%;
  margin-top: -50px;
  margin-left: -50px;
}

Explore more

Notice the placement as you:

  1. Add top and left values set to 0px.

    1. What does this do and why?

  2. Change top and left to 100px, to 50%, 5em.

  3. Choose different values for top and left.

  4. Set squareBlue back to 0px for both top and left.

  5. Add a another square (squareRed) with width and height set to 150px. 1. Where was it placed? What happens when you swap the squareBlue and squareRed classes in the HTML?

  6. Play around with top and left values of squareRed.

Where you set the position property of an element is important both in html and css

Challenges

Gold':'

Center the blue square on the document

Blue':'

Center the red square inside the blue square

Challenge Answer

  1. Set squareBlue top(x) & left(y) to 50%. If squareRed top & left values are set to 50% as well, what do expect? inside squareBlue. The left top corner is the anchor point for the element and therefore the point at which the element will be placed on the document (or in relation to its ancestor)

  2. Add a margin-top & a margin-left with a negative value which is 1/2 the square's width and 1/2 the square's height to both squares. This should center the square.

.absolute{
  position: absolute;
  width: 200px;
  height: 200px;
  background: blue;
  border: 4px solid blue;
  top: 50%;
  left: 50%;
  margin-top: -50px;
  margin-left: -100px
}

.absolute2{
  position: absolute;
  width: 150px;
  height: 150px;
  background: orangered;
  top: 50%;
  left: 50%;
  margin-top: -25px;
  margin-left: -70px

Last updated