How to center absolute positions

I want to absolutely position the text on top of my image, but it does not seem to be the center. I tried something, but it was very strange. I'm going to a responsive site, but with that it starts to seem weird. here is my code.

HTML

<div id="container"></div>
<div class="parent">
    <div class="child">
        <h1> Richy Photography </h1>
    </div>
</div>

CSS

#container {
    position:absolute;
    top:0;
    left:0;
    width:100%;
    height:100%;
    background-image:url(image.jpg);
    background-size:cover;
    background-position:50% 50%;
    background-repeat: no-repeat;
}
body, html
{
    height:100%;
    width:100%;
}
.parent {
    position:relative;
    font-family: Helvetica, Arial, sans-serif;
    width: 100%;
    height: 100%;
    margin:0;
    padding:0;
}

.child {
    position: absolute;
    left:37%;
    top:37%;
    margin:0;
    padding:0;
}
+3
source share
4 answers

Due to 37% of the top and left offsets, the text will be displayed on the screen if the viewport is too small.

A simpler solution would be to simply set your element .parentto display in the view table, and then set your element .childto display in the view table-cellwith horizontal and vertically aligned content:

.parent {
    display: table;
    height: 100%;
    width: 100%;
}

.child {
    display: table-cell;
    text-align: center;
    vertical-align: middle;
}

JSFiddle demo .

IE8 .

, , .parent z-index :

.parent {
    display: table;
    height: 100%;
    position: relative;
    width: 100%;
    z-index: 2;
}

JSFiddle.

.parent #container.

+4

, , :

.child {
position: absolute;
text-align:center;
margin:0;
padding:0;
width:100%;
}

, text-align: center

+1

You cannot rely on the left: 37%; to center your element on different screen sizes. Try it left: 0; text-align: center; width: 100%;, this should contain the element .childin the center, no matter what size the parent is.

If you really need a position: absolute; try this, otherwise go with @James Donnelly to answer, this is the dough.

Good luck and good luck in your project.

+1
source

Setting the left and right margins to auto, adding width and using left: 0; and to the right: 0; must work.

Something like that:

.child {
  position: absolute;
  top: 0;
  width:26%;
  margin: 0 auto;
  left:0;
  right:0;
}
+1
source

All Articles