Sergi
Sergi

Reputation: 1240

Absolute positioned element - Top percentage not working

What could be the cause for an absolute positioned element to ignore a percentage for the "top" position? Percentages are working for "left", and I can use pixels and vh to position it vertically, just not a percentage.

Upvotes: 0

Views: 2066

Answers (3)

slevy1
slevy1

Reputation: 3832

As it turns out there are multiple ways to absolutely position an element. Here is one way without using a parent DIV:

CSS:

   html,body {
    width:100%;
    height:100%;
    background:red;
   }
    .centered-axis-xy {
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%,-50%);

} 
div.cyan5050 {
    width:50%;height:50%;
    background:cyan;
}
div p {
    width:100%;
    height:50%;
    margin-top: 20vh;
    text-align:center;
}

HTML:

<div class="cyan5050 centered-axis-xy">
        <p>Content to Display</p>
</div>


See fiddle

Normally, if you use percentages one needs to provide a basis for the percentages of the DIV tag, namely the height and width percentages of a containing outer DIV or else with respect to the html and body elements. But, in this case, since the CSS incorporates a responsive positioning technique mentioned here, the percentages for the html and body elements are optional thanks to the CSS transform being equipped with a translate() function.

Upvotes: 0

Sanchit Goel
Sanchit Goel

Reputation: 141

You need to define a layout to its parent element.

Layout could be other than 'static' like 'fixed', 'absolute', 'relative'

This will help browser to understand that calculations of percentage need to be done in realtion to its parent and not the window size.

Upvotes: 0

johnpro
johnpro

Reputation: 29

This is because you have to make the parent of the absolute element - "position: relative". So then the absolute element's top and left fields will get the applied values relative to parent.

Upvotes: 2

Related Questions