Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
490 views
in Technique[技术] by (71.8m points)

css - Absolute positioning inside relative positioning?

According to W3Schools (http://www.w3schools.com/css/css_positioning.asp):

Relatively positioned elements are often used as container blocks for absolutely positioned elements.

Why is this? Is there a good example?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

A good example would be when you want to position something to the page or "relative" to a container/div.

Here is my Fiddle http://jsfiddle.net/doitlikejustin/RdWQ7/2/

This shows you that without the absolute div being inside of a "relative" div, the contents are aligned to the document body.

Notice that the green div (#box1), which has position: relative, the div inside (#inner1) it is aligned top/right INSIDE of #box1.

The blue box (#box2), which has the exact same HTML layout as the green box (#box1), does NOT include position: relative and notice that the div inside it (#inner2) is aligned to the top/right of the body

#box1, #box2 {
    width: 100px;
    height: 100px;
    color: white;
    text-align: center;
    line-height: 100px;
}
#box1 {
    background: green;
    position: relative;
}
#box2 {
    background: blue;
}

#inner1, #inner2 {
    width: 50px;
    height: 50px;
    top: 0;
    right: 0;
    position: absolute;
    background: black;
    opacity: 0.5;
    color: white;
    text-align: center;
    line-height: 50px;
}

Here is a good article about it from Chris Coyier...

A page element with relative positioning gives you the control to absolutely position children elements inside of it.

Source: http://css-tricks.com/absolute-positioning-inside-relative-positioning/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...