CSS中的绝对定位

CSS中的绝对定位

左直拳

我发现,CSS中的绝对定位并不如印象中的那样,一定要给lefttop一个具体特定的数值,如:

<div id="divClosestool" style="position:absolute;left:100px;top:100px;background-color:Red;font-size:18pt;color:Yellow;">一人有一只马桶</div>

其实用相对值也是可以的:

<div id="div1" style="position:absolute;left:50%;top:50%;background-color:Red;font-size:18pt;color:Yellow;"><b>在水中央</b></div>

这样就真的显示在页面中央。

还可以使用“auto”。

auto”应该是自动。怎么个自动法?

我也不清楚。不过,因为想做个下拉菜单的缘故,就应用了一回。大姑娘坐花轿,头一回。

得出的结论是元素会自动受所在容器约束。

<table border="1" style="450px;" align="center">

<tr><td align="center" width="33%">谎言</td><td align="center" width="33%">可恶的谎言</td><td align="center" width="33%">TMD可恶的谎言</td></tr>

    <tr>

        <td>

        </td>

        <td>

        </td>

        <td>

        <div id="div2" style="position:absolute;left:auto;top:auto;background-color:Green;font-size:18pt;color:white;200px;height:150px;z-index:-1;"><b>狗屎</b></div>       

        </td>

    </tr>

    <tr>

        <td colspan="3" style="color:Red;">十天九地菩萨摇头怕怕霹雳金光雷电掌。一掌打出,方圆几百里无论人畜虾蟹都化为飞灰

        </td>

    </tr>

</table>

其实写在单元格<td>里的内容都受单元格的约束,不管有没有绝对定位。但为什么还要用绝对定位?我认为绝对定位有一个很大的好处,就是超然于页面格局排布之外,不受周围的元素位置影响。

结果将以上HTML代码放在一个页面中,即会产生如下结果:

 (csdn的blog真烂)

完整代码如下:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >

<head>

    <title>左直拳摆地摊</title>

</head>

<body>

<div id="divMenu" style="position:absolute;left:100px;top:100px;background-color:Blue;font-size:18pt;color:Yellow;"><b>一人有一只马桶</b></div>

<div id="div1" style="position:absolute;left:50%;top:50%;background-color:Red;font-size:18pt;color:Yellow;"><b>在水中央</b></div>

<table border="1" style="450px;" align="center">

<tr><td align="center" width="33%">谎言</td><td align="center" width="33%">可恶的谎言</td><td align="center" width="33%">TMD可恶的谎言</td></tr>

    <tr>

        <td>

        </td>

        <td>

        </td>

        <td>

        <div id="div2" style="position:absolute;left:auto;top:auto;background-color:Green;font-size:18pt;color:white;200px;height:150px;z-index:-1;"><b>狗屎</b></div>       

        </td>

    </tr>

    <tr>

        <td colspan="3" style="color:Red;">十天九地菩萨摇头怕怕霹雳金光雷电掌。一掌打出,方圆几百里无论人畜虾蟹都化为飞灰

        </td>

    </tr>

</table>

</body>

</html>

 

 
原文地址:https://www.cnblogs.com/leftfist/p/4258315.html