绝对位置影响宽度? [英] absolute position affects width?

查看:33
本文介绍了绝对位置影响宽度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 css 新手.我想知道为什么当我将div元素的定位更改为absolute时,div元素的宽度会发生变化?在 Chrome v25.0.1364.172m 和 IE9 中试过,结果相同.

简单例子:

<头><title>test</title><风格>div {位置:相对;边框宽度:1px;边框样式:实心;边框颜色:黑色;}</风格><身体><div>测试</div>

解决方案

因为绝对定位的元素不像块级元素,并且不会像正常的 a

那样相互流动.

您需要为绝对定位的 div 设置宽度和高度,具体取决于它包含的内容.

绝对定位的元素将相对于它所在的第一个父元素进行定位.所以,一个简单的例子:

一个简单的陷阱"不是将父元素设置为具有 position:relative;

<div style="width: 500px; height: 500px; position: relative; border: 1px solid blue;"><!-- 我是上述父元素的子元素--><div style="width: 150px; height: 150px; position: absolute; left: 10px; top: 10px; border: 1px solid red;">我绝对定位于我的父母.

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>

解决方案

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>

这篇关于绝对位置影响宽度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
前端开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆