简体   繁体   English

来自兄弟元素的CSS边距顶部不是父元素

[英]CSS margin top from sibling element not parent

I have got this html 我有这个HTML

 <div class="ChatDiv">
    <div class="chatdiv_ fm">
            <span>uhygtfgyhujiuhygt i uytr yui jhuygtfr</span>
    </div>
    <div class="chatdiv_ fm" style="margin-top:148;">
           <span>t</span>
    </div>

<div class="chatdiv_ fm" style="margin-top:214;">
                        <span>t</span>
          </div>
   </div>

And this css 而这个CSS

.ChatDiv{
    width: 800px;
    height: 480px;
    overflow: auto;
    margin-left: 350px;
    border-radius: 4px;
    background: white;
    margin-top: 80px;
    position: absolute;
    box-shadow: 0px 0px 11px black;
}
.fm{
    position: relative;
    font-family: Nbutler;
    font-size: 20px;
    float: right;
    background: #2196f3;
    max-width: 400px;
    color: white;
    margin-left: -432px;
    margin-right: 20px;
    padding: 10px;
    border-radius: 5px;
    span{
        display: block;
        height: auto;
        width: auto;
        max-width: 400px;    
    }
}

And the problem is when i have margin top on fm elements it takes this margin from the top.Not from the sibling element and i do not how many fm elements i will have so i can not put the same margin-top for all fm elements 问题是当我在fm元素上有margin顶部时,它从顶部开始取这个margin。不是从同级元素中获取,我也没有多少fm元素,所以我不能为所有fm元素放相同的margin-top

If you want to use absolute position, then it will happen all the time, because it will a Div, which has position relative as a borders, and your divs with position absolute just "doesnt exit". 如果您要使用绝对位置,那么它会一直发生,因为它将是一个Div,具有相对的位置作为边界,并且绝对位置的div只是“不退出”。

There's no need to use position: absolute for these divs. 无需使用position: absolute这些div的position: absolute Just remove float, position, margins and you will good to go. 只需除去浮标,头寸,边距,您就可以走了。

jsFiddle: https://jsfiddle.net/sey4121b/ jsFiddle: https ://jsfiddle.net/sey4121b/

Added Example where margins are calculated from siblings. 添加了示例,其中的边距是根据兄弟姐妹计算的。

 .container{ width: 500px; height: 300px; margin: 16px auto; padding: 16px; border-radius: 6px; border: 1px solid black; } .list { box-sizing: border-box; padding: 16px; float: right; width: 50%; height: 100%; background-color: tomato; } .list__elem { box-sizing: border-box; width: 100%; height: 42px; margin-bottom: 16px; padding-left: 16px; border: 1px solid olive; line-height: 40px; } 
 <div class="container"> <ul class="list"> <li class="list__elem">Elem 1</li> <li class="list__elem">Elem 2</li> <li class="list__elem">Elem 3</li> <li class="list__elem">Elem 4</li> </ul> </div> 

I think that inline margin styles and lack of element grouping makes it hard to understand the example. 我认为行内页边距样式和元素分组的缺乏使示例难以理解。

Good luck ;) 祝好运 ;)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM