markus
markus

Reputation: 267

CSS3 set div margin based on siblings child height

I have an html structure like in the following fiddle http://jsfiddle.net/szpali76/62frb9n6/3/

<div>
<div id="user">
    <div>John Smith, premium user</div>
</div>
<div class="post">
    <div>
        <div class="postTitle">This is a really long long long title with lot of contents ... fgdsfgdfgdsfgdsfgdfgg dsdfgsdfgdfgdsfgfg dfsdfgdsfgdsfgdfg dsf gsdfgsdfgdsfgdfhdfghdfgdfghfdghfghsfgdfsgsdfgdsfgdsgdsf</div>
        <div class="postContent">gsdfgdsfgdfsgdfsgdsfg</div>
        <div class="reply"><a>Reply</a></div>
    </div>
</div>

and the css is

.postTitle {
   font-weight: bold;
   padding: 10px;
   background-color: yellow;
}
#user {
    margin-top: 20px;
    padding: 10px;
    color: white;
    background-color: green;
}
.postContent {
   background-color: orange;
   padding: 10px;
}
.reply{
   background-color: brown;
   padding: 10px;
}

Is there a CSS way to set a style on tagname with id='user' and push it bellow the div with postTitle class name, I cannot change the HTML structure. The div.postTitle changes it's content based on the user input, so it doesn't have a fix height.

Upvotes: 1

Views: 360

Answers (2)

Paulie_D
Paulie_D

Reputation: 114990

I don't think so..If you can't change the HTML then you will have to use JS since CSS can't adjust the properties of a previous element based on a later one

Jquery Solution

$(document).ready(function() {
  $("#user").clone().insertAfter('#postTitle');
  $("#user").remove();
});
.postTitle {
  font-weight: bold;
  padding: 10px;
  background-color: yellow;
}
#user {
  padding: 10px;
  color: white;
  background-color: green;
}
.postContent {
  background-color: orange;
  padding: 10px;
}
.reply {
  background-color: brown;
  padding: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <div id="user">
    <div>John Smith, premium user</div>
  </div>
  <div class="post">
    <div>
      <div id="postTitle" class="postTitle">This is a really long long long title with lot of contents ... fgdsfgdfgdsfgdsfgdfgg dsdfgsdfgdfgdsfgfg dfsdfgdsfgdsfgdfg dsf gsdfgsdfgdsfgdfhdfghdfgdfghfdghfghsfgdfsgsdfgdsfgdsgdsf</div>
      <div class="postContent">gsdfgdsfgdfsgdfsgdsfg</div>
      <div class="reply"><a>Reply</a>
      </div>
    </div>
  </div>
</div>

Upvotes: 3

ngjeorgjiev
ngjeorgjiev

Reputation: 61

This might be a bad solution, but here goes:

#user {
position:absolute;
...
}

Use this to position your other elements, used jQuery it can be done with pure javascript also.

var titleHeight = document.getElementById('postTitle');
var userHeight= document.getElementById('user');
$("#user").css("margin-top",titleHeight.clientHeight)
$(".postContent").css("margin-top",userHeight.clientHeight)

JSFIDDLE example

Hope it helps.

Upvotes: 0

Related Questions