加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 资源网站 > 资源 > 正文

html – 表内的绝对定位

发布时间:2020-12-14 22:44:46 所属栏目:资源 来源:网络整理
导读:我需要在td中定位具有绝对定位的东西.为了解决在将td设置为relative时未定义td的事实,我在我的td中使用div设置为relative,然后在div中我将内部div设置为absolute.当我的内容填满td时,这一切都很有效.当我将td的内容设置为none时,绝对定位会全部搞砸. 有谁知

我需要在td中定位具有绝对定位的东西.为了解决在将td设置为relative时未定义td的事实,我在我的td中使用div设置为relative,然后在div中我将内部div设置为absolute.当我的内容填满td时,这一切都很有效.当我将td的内容设置为none时,绝对定位会全部搞砸.

有谁知道为什么会这样.

HTML:

和CSS:

td{
    border:1px solid red;
    width:100px;
    height:60px;
    vertical-align:bottom;
}

.slot{
  width:100px;
  height:29px;
  background-color:#999;
  border:1px dashed blue;
}

.relative{
    position:relative;
}

.absolute{
    position:absolute;
    top:5px;
    left:5px;
}
.hidden{
    display:none;
}

现场版:http://jsfiddle.net/HgEtQ/

在上面的小提琴中,您可以看到第一个表格单元格正常工作.绝对定位的div位于正确的空间中.第二个隐藏了顶部插槽,现在绝对定位不再位于左上角.如果你取出两个插槽,那么它确实搞砸了绝对定位.我需要将它定位为绝对值,因为某些元素会根据元素移动.

最佳答案
这里有几件事情要发生.

你有这个:

td {
    /*...*/
    vertical-align:bottom;
}

这将把细胞的内容推到底部.

此外,绝对定位的元素是removed from the normal flow,因此它不会对其父级的高度做出贡献:

It is removed from the normal flow entirely (it has no impact on later siblings). An absolutely positioned box establishes a new containing block for normal flow children and absolutely (but not fixed) positioned descendants.

特别是,这意味着你的div.relative元素的高度为零,但它们仍然会有一个左上角,所以你的绝对定位偏移量会被固定在某个地方.

然后你有< div class =“slot hidden”>并隐藏删除< div>从布局,所以你有效地拥有这个:

结合vertical-align:bottom意味着你的第二个div.absolute将位于div.slot顶部5px,距离表格底部25px.

第一个单元格工作正常,因为两个可见的div.slot元素将div.relative右推到单元格的顶部,然后div.absolute位于div.relative顶部5px,距离顶部5px表格单元格.

不幸的是,添加位置:相对于< td>对于浏览器来说有点狡猾,所以你需要一些hackery来保持你的定位,同时保持vertical-align:bottom.您可以像这样重新组织< td>:

这样的CSS:

td{
    border:1px solid red;
    width:100px;
    height:60px;
    vertical-align: top;
}

.slot{
    width:100px;
    height:29px;
    background-color:#999;
    border:1px dashed blue;
}

.relative {
    position:relative;
}
.nonsense {
    height: 62px; /* td[height] + 2 for the borders */
    display: table-cell;
    vertical-align: bottom;
}

.absolute{
    position:absolute;
    top:5px;
    left:5px;
}
.hidden{
    display:none;
}

实例:http://jsfiddle.net/ambiguous/aV4nT/

或者你可以使用visibility: hidden

hidden
The generated box is invisible (fully transparent,nothing is drawn),but still affects layout. Furthermore,descendants of the element will be visible if they have ‘visibility: visible’.

你的.hidden类代替display:none:

.hidden {
    visibility: hidden;
}

这将使div.slot元素占用空间并影响布局,但只会看到第二个.

实例:http://jsfiddle.net/ambiguous/RcdNh/

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读