Search code examples
htmlcssborderpseudo-class

Applying a proper border to elements using float:left


(See the actual question below the line, read the upper description if you need more explanation).

In CSS, :last-child and :first-child give me good options to work with. Tables come with , strong text and more tags that i can target using CSS selectors, so with these tools it is easy to put a proper border around all the cells of the table, without having double borders appearing on any sides.

Applying this to a list of DIVs with each appearing below the other, it is a simple thing as well, as all i need to do will be to remove the bottom border on the last child.

But:


When i use a list of DIVs that float next to one another, say, for example 3 in a row (before their sum of widths exceeds the width of the target container and cause them to wrap), i always end up with some double borders on some sides.

Is there a neat and clean CSS solution to this?


Solution

  • I think the kind of solution you're looking for simply isn't possible. When you're using a table, the browser can understand that the td and th elements all belong to the same tr and come up with simple rules for determining how they look as a group.

    Divs on the other hand are highly variant (rightfully so) and don't really have a way to create that sort of association using purely html and css. There is no way to semantic way to say something like the children of this div are going to be on the same row, so they should all share a border.

    The workaround is easy enough:

    http://jsfiddle.net/8uqae/

    Simply create a special class for a div at the end, and then give the rest of the divs a border on the right side.

    HTML:

    <div>
      <div class="left-end fl"></div>
      <div class="middle fl"></div>
      <div class="middle fl"></div>
      <div class="middle fl"></div>
      <div class="middle fl"></div>
      <div class="middle fl"></div>
      <div class="clr"></div>
    </div>​
    

    CSS:

    .fl {
      float: left;
    }
    .clr {
      clear: both;
    }
    .left-end, .middle {
        width: 30px;
        height: 20px;
        margin: 0;
        padding: 0;
        border-top: solid 1px black;
        border-right: solid 1px black;
        border-bottom: solid 1px black;
    }
    
    .left-end {
      border-left: solid 1px black;
    }
    

    As srini pointed out, there are frameworks out there which assist in this and are worth looking into. Cross-browser responsive div layout on screens of various sizes can be tricky so considering a framework like Twitter Bootstrap, among others, is worth the thought.