龙空技术网

CSS 父元素中的绝对定位

寒笛过霜天 43

前言:

今天各位老铁们对“html字体靠右侧”可能比较讲究,各位老铁们都想要分析一些“html字体靠右侧”的相关资讯。那么小编在网摘上汇集了一些有关“html字体靠右侧””的相关内容,希望姐妹们能喜欢,大家一起来学习一下吧!

用position属性实现绝对定位

<html><head><title>position属性</title><style type="text/css"><!--body{    margin:10px;    font-family:Arial;    font-size:13px;}#father{    background-color:#a0c8ff;    border:1px dashed #000000;    width:100%;    height:100%;}#block{    background-color:#fff0ac;    border:1px dashed #000000;    padding:10px;    position:absolute; /* absolute绝对定位 */    left:20px; /* 块的左边框离页面左边界20px */    top:40px; /* 块的上边框离页面上边界40px */}--></style></head><body><div id="father"><div id="block">absolute</div></div></body></html>

以上的代码我们可以看出父块#father没有设置position属性,而子块#block采用的是绝对定位,经过测试发现子块#block参照浏览窗口左上角

为原点,子块左边框相对页面<body>左边的距离为20px,子块的上边框相对页面<body>上面的距离为40px

为父块这是position属性

#father{    background-color:#a0c8ff;    border:1px dashed #000000;    position:relative;    width:100%;    height:100%;}

我们发现子块的参照物为父块的#father,距左侧20px,距上端40px

注意top、right、bottom、left这4个CSS属性,它们都是配合position属性使用的,表示的是块的各个边界离页面边框(position设置为absolute时)

或者原来的位置(position设置为relative)的距离。只有当position属性设置为absolute或者relative时才能生效;

用position属性实现相对定位

<html><head><title>position属性</title><style type="text/css"><!--body{    margin:10px;    font-family:Arial;    font-size:13px;}#father{    background-color:#a0c8ff;    border:1px dashed #000000;    width:100%; height:100%;    padding:5px;}#block1{    background-color:#fff0ac;    border:1px dashed #000000;    padding:10px;    position:relative; /* relative相对定位 */    left:15px; /* 子块的左边框距离它原来的位置15px */    top:10%;}--></style></head><body><div id="father"><div id="block1">relative</div></div></body></html>

我们可以看到字块的左边框相对于其父块的左边框(它原来所在的位置)距离为15px,上边框也是一样的道理,为10%;

理解"它原来的位置":子块和父块原先的位置的是一致的(因为父块包含字块,视觉上看是几乎重叠的)

此时子块的宽度依然是未移动前的宽度,撑满未移动前父块的内容。只是由于向右移动了,因此右边框超出了父块。

如果希望子块的宽度仅仅为其内容加上自己的padding值,可以将它的float属性设置为left,或者指定其宽度width;

案例: 文本在图片上显示

<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8" /><title>Document</title><style type="text/css">*{    margin: 0;    padding: 0;}div{    width: 200px;    height: 200px;    margin: 100px auto;    border: 1px solid red;    position: relative;}img{    vertical-align: top; /* 解决图文间歇问题 */}p{    color: #fff;    width: 200px;    height: 40px;    font-size: 14px;    line-height: 40px;    background-color: rgba(0, 0, 0, 0.5);    text-align: center;    position: absolute;    left: 0;    /* top: 160px; */    bottom: 0;}</style></head><body><div><img src="img/tb.webp" alt=""><p>箱子箱子箱子箱子箱子</p></div></body></html>

标签: #html字体靠右侧 #html relative定位 #html父级元素 #绝对定位代码 #绝对定位代码怎么打