Zamboni
Zamboni

Reputation: 335

Divs won't align to the right

I am trying to create a messaging page, but the divs with the sent messages stack up---there are two in each "row" when there should only be one.

The divs with the class of .message should all float to the right, with only one div per line.

I am using jQuery in my project.

#mydiv{
  width: 80%; 
  margin: auto;
  min-height: 100px;
  max-height: 80%;
  overflow-y: auto;
  border: 3px solid red;
}

.message{
  float: right;
  width: 40%;
  border: 2px solid aqua;
}

#messagebox{
  position: absolute;
  right: 11%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<head>
</head>
<body>
<div id="mydiv">

</div>
<p/>
<textarea id="messagebox" placeholder="Press enter to send message">
</textarea>
<script>
$('#messagebox').keypress(function(e){
	if(e.which==13){
  	e.preventDefault();
    send($(this).val());
    $(this).val("");
  }
});
function send(msg){
 var msgDiv = "<div class='message'>"+msg+"</div>"
	$('#mydiv').append(msgDiv);
}
</script>
</body>
</html>

Upvotes: 4

Views: 72

Answers (1)

Unmitigated
Unmitigated

Reputation: 89254

You will need to use clear: both to prevent any floating elements of either side of the .message divs (or you can just use clear: left to prevent any floating elements to the left of the .message divs). See the documentation.

#mydiv{
  width: 80%; 
  margin: auto;
  min-height: 100px;
  max-height: 80%;
  overflow-y: auto;
  border: 3px solid red;
}

.message{
  float: right;
  width: 40%;
  clear: both;/*prevents floating elements on both sides*/
  border: 2px solid aqua;
}

#messagebox{
  position: absolute;
  right: 11%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<head>
</head>
<body>
<div id="mydiv">

</div>
<p/>
<textarea id="messagebox" placeholder="Press enter to send message">
</textarea>
<script>
$('#messagebox').keypress(function(e){
  if(e.which==13){
    e.preventDefault();
    send($(this).val());
    $(this).val("");
  }
});
function send(msg){
 var msgDiv = "<div class='message'>"+msg+"</div>"
 $('#mydiv').append(msgDiv);
}
</script>
</body>
</html>

Upvotes: 2

Related Questions