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

Categories

I am new to css. I am wondering why when I change the positioning of the div element to absolute, the width of the div element changes? Tried it out in Chrome v25.0.1364.172m and IE9, both have the same outcome.

Simple example:

<!doctype html/>
<html>
<head>
    <title>test</title>
    <style>
        div {
            position:relative;
            border-width: 1px;
            border-style: solid;
            border-color: black;
        }
    </style>
</head>
<body>
    <div>test</div>
</body>
</html>
See Question&Answers more detail:os

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

1 Answer

Because absolutely positioned elements do not behave as block level elements and do not flow after each other like normal a<div>does.

You will need to set a width and a height for a div that is absolutely positioned, depending what it contains.

Your absolutely positioned element will position relative to the first parent element it is in. So, a simple example:

A simple 'gotcha' is not setting the parent element to have position: relative;

<!-- I'm a parent element -->
<div style="width: 500px; height: 500px; position: relative; border: 1px solid blue;">

    <!-- I'm a child of the above parent element -->
    <div style="width: 150px; height: 150px; position: absolute; left: 10px; top: 10px; border: 1px solid red;">
         I'm positioned absolutely to my parent. 
    </div>

</div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...