首页 > 解决方案 > 在网络日历中定位 div 元素的问题

问题描述

我正在编写一个 html 日历并被困在定位 div 上。我动态生成 div,它们相互堆叠,这在大多数情况下都可以。有时我需要创建一个 div 并将其放置在页面顶部的第一个创建的 div 旁边。如果我使用浮动,它会移动得太远并且不会到达顶部。我可以使用位置来完成此操作,但它变得复杂。看起来应该很容易将它放到顶部,就像在使用 valign=top 的表中一样。我添加了一些 css 定位来显示我想要 div 的位置,但如果可能的话,我想在没有位置的情况下这样做。任何关于定位 div 的好方法的建议将不胜感激。

#container{
  width:200px;
  height:200px;
  background-color:blue;
}

#item1{
  width:50px;
  height:50px;
  background-color:red;
}

#item2{
  width:50px;
  height:50px;
  background-color:yellow;
}

#item3{
  width:50px;
  height:50px;
  background-color:green;
  float: right;
  position:relative;
  top:-100px;
  left:-100px;
}
<div id=container>
  <div id=item1></div>
  <div id=item2></div>
  <div id=item3></div>
</div>

标签: javascripthtmlcss

解决方案


也许您应该考虑在单元格中使用网格布局。您可以更好地控制内容在单元格中的显示方式,而无需使用浮动 div。此外,网格容器中的布局可以使事物保持统一并防止重叠使用

grid-template-columns: auto auto auto;

如果您只想要顶部的 2 列,只需将其更改为

grid-template-columns: auto auto ;

这是一个链接网格布局

弹性盒与网格

#container{
  width:200px;
  height:200px;
  background-color:blue;
display: grid;
grid-gap: 2px;
grid-template-columns: auto auto auto;
grid-template-rows: 60px auto auto;
}

#item1{

  width:50px;
  height:50px;
  background-color:red;
}

#item2{
  width:50px;
  height:50px;
  background-color:yellow;
}

#item3{
  width:50px;
  height:50px;
  background-color:green;

 
  
}
<div id=container>
  <div id=item1></div>
  <div id=item2></div>
  <div id=item3></div>
    <div id=item3></div>
      <div id=item3></div>
       <div id=item1></div>
        <div id=item1></div>
         <div id=item1></div>
</div>


推荐阅读