COp
COp

Reputation: 25

CSS margin top from sibling element not parent

I have got this 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

.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

Upvotes: 0

Views: 3217

Answers (2)

karlisup
karlisup

Reputation: 682

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 ;)

Upvotes: 0

Paulius K.
Paulius K.

Reputation: 210

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".

There's no need to use position: absolute for these divs. Just remove float, position, margins and you will good to go.

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

Upvotes: 1

Related Questions