Andrew Perry Andrew Perry - 18 days ago 5
CSS Question

How do I format boxouts in css

I'm writing some documentation for some VBA code I wrote, and I'm trying to add boxouts for comments to add notes. In the past I've always just floated them off to the right, but now that I need to comment sequential lines there's not always enough space for the comment on a single line. The upshot is that the comments end up staggered horizontally to fit them all in.

staggered versus stacked boxouts

What I'd like to do is make the boxouts stack and make the text they're floated next to shuffle down a bit to make space.

Can it be done? My HTML/CSS skills are a bit rusty and from the 4.01 days...

EDIT: There's not much code to show - so far I only have this:

.boxcomment {
width: 25%;
float: right;
clear: both;
}


That successfully stacks the boxouts, but they end up misaligned with the associated code line.

EDIT: Here's an example of the alignment issue:

HTML

<!doctype html>
<html>
<head>
<title>Calculator Documentation</title>
<link rel="stylesheet" type="text/css" href="default.css">
</head>

<body>

<!-- Header -->

<!-- Navigation -->

<!-- Content -->

<div style="width:40%;">

<div class="boxcomment">Comment is way too long Comment is way too long Comment is way too long Comment is way too long </div>
<pre>Some random code and some more code</pre>
<div class="boxcomment">Another comment</div>
<pre>More code</pre>

</div>

<!-- Footer -->

</body>

</html>


CSS

.boxcomment {
width: 25%;
float: right;
clear: both;
border: 1px #000;
background-color: silver;
margin: 10px;
}


That gives this result, where the second comment isn't aligned with the paragraph it accompanies. (Coloured lines indicate where they should line up.)

Showing misaligned text

Does that make the question any clearer? It's a bit fuzzy, I know...

EDIT: Expanded the HTML by request to include the whole code.

Answer

Use clearance:

9.5.2 Controlling flow next to floats: the 'clear' property

This property indicates which sides of an element's box(es) may not be adjacent to an earlier floating box.

Values other than 'none' potentially introduce clearance. Clearance inhibits margin collapsing and acts as spacing above the margin-top of an element. It is used to push the element vertically past the float.

Like this:

clear: right;

.boxcomment {
  width: 25%;
  float: right;
  clear: right;
  border: 1px #000;
  background-color: silver;
  margin: 10px;
}
pre::after {
  content: '';
  display: block;
  clear: right;
}
<div class="boxcomment">Comment is way too long Comment is way too long Comment is way too long Comment is way too long </div>
<pre>Some random code and some more code</pre>
<div class="boxcomment">Another comment</div>
<pre>More code</pre>