FlyingCat
FlyingCat

Reputation: 14250

How to position the element using absolute position?

I am trying to create a responsive design for my app.

I have a big background image and it will show the full size when user has large screen and only show partial if user uses small screen.

I want to place few elements on my app with absolute position but the problem is I can't lock their top and left value because the screen size changes.

I have something like

css

#background{
    background: url('BG.jpg') no-repeat top center fixed;
    width: 1900px;
    height: 1200px; 
}

#element{
   position: fixed;
   z-index: 5;
   top: 50%;   //looks fine in 1900 x 1200 screen but position is off on 1200 x 1000
   left:70%; //looks fine in 1900 x 1200 screen but position is off on 1200 x 1000
}

html

<div id='background'></div>
<img id='element' src='test.jpg' />

How do I keep the position of the element on the same spot when user has small screen? Thanks for the help!

Upvotes: 2

Views: 300

Answers (2)

CodeViking
CodeViking

Reputation: 206

Consider making a javascript function that calculates the screen width. After that add margin-left to #background equal to ( screen width / -2 ). Make #background width & height - 100%

Upvotes: 0

Joseph Marikle
Joseph Marikle

Reputation: 78520

When using position: absolute, you need to make sure that it has a parent with a position attribute other than the default (which is static). If there is no such parent, the document is the effective parent. For your example, I would advise making the img#element a child of div#background like so

<div id='background'>
    <img id='element' src='test.jpg' />
</div>

and then adding position:relative; to the #background css style

#background{
    background: url('BG.jpg') no-repeat top center fixed;
    width: 1900px;
    height: 1200px;
    position: relative;
}

The reason relative is used, is because it doesn't take the element out of the document flow (like fixed or absolute would) and as long as you don't specify a top, left, 'bottom', or right attribute to the parent (#background in the case), it will stay in the same location as it would with default positioning.

Edit:

I don't think this will work out of the box for you. You need to figure out how to make the image's width dynamic as well. You can either give it a % based width or use media queries.

Edit 2:

Ia also just noticed you have position:fixed for img#element. Change that to position:absolute. that will make it so that it is positioned relative to the position:relative parent rather than the window.

Upvotes: 1

Related Questions