0

Just as the title indicates, I'm trying to horizontally and vertically center an absolutely positioned element. Here is a plunker of my attempt based on other posts I've found. The goal is to have the red ALERT text to be centered within the outlined box.

And here is the CSS:

.parent {
  position: relative;
}
.child {
  bottom: 0;
  color: red;
  left: 0;
  margin: auto;
  position: absolute;
  right: 0;
  top: 0;
}
mellis481
  • 4,332
  • 12
  • 71
  • 118

3 Answers3

1

A couple of things: for something to be centered, the parent container needs to have a height. Be it height created by other content, or simply a predefined height. I have removed your .parent and you will see the .child actually centering inside the container. Your container also needs a relative position (or any position property other than static), so the absolute centering is in relation to that element.

Lastly, we can use a simply technique to center your box by moving it 50% right, 50% down and then moving it back by half of its width and height. The moving back uses translation:

.container {
  border: 1px solid black;
  // We need the container we want to center in to have a positioned value
  position: relative;
}
.child {
  position: absolute;
  top: 50%;
  left: 50%;
  -webkit-transform: translate(-50%,-50%);
  transform: translate(-50%,-50%);
}
<div class="container">
  <div class="child">ALERT</div>
  <p>Item here</p>
  <p>Item here</p>
  <p>Item here</p>
  <p>Item here</p>
  <p>Item here</p>
  <p>Item here</p>
  <p>Item here</p>
  <p>Item here</p>
</div>
somethinghere
  • 16,311
  • 2
  • 28
  • 42
0

Try positioning absolute the parent (you have to set a height):

JSFiddle

.container {
    position: relative;
    border: 1px solid black;
}

.parent {
    position: absolute;
    bottom: 0;
    color: red;
    left: 0;
    top: 0;
    right: 0;
    width: 100%;
    height: 16px;
    margin: auto;
    text-align: center;
}
Kostas Mitsarakis
  • 4,772
  • 3
  • 23
  • 37
0

A neat thing with Html is that you can use percentiles instead of pixels to describe relativity. For example:

instead of using:

bottom: 250px;

you can use something like:

right: 43%;

using that along with calculated proportions, such as:

top:45%
bottom: 45%;

and setting the text height to 10%, you can have anything you want centered.

judging by your code you're already familiar with "auto" so I'll save you that song and dance.

DJHakim
  • 133
  • 1
  • 11