Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS: selecting the last float <li> on the same horizontal row [duplicate]

Tags:

css

css-float

I am using the following CSS for arranging list of boxes:

 li {
     display: block;
     float: left;
 }

I'd like to carefully tune margins of <li> items so that the last item on the row (horizontal span) would get different margins.

Are there any CSS selectors which could target float elements based on their position?

like image 222
Mikko Ohtamaa Avatar asked Jan 27 '12 23:01

Mikko Ohtamaa


People also ask

How do you target the last element in CSS?

The :last-of-type selector allows you to target the last occurence of an element within its container. It is defined in the CSS Selectors Level 3 spec as a “structural pseudo-class”, meaning it is used to style content based on its relationship with parent and sibling content. ).

Why is last child not working?

:last-child will not work if the element is not the VERY LAST element. I think it's crucial to add/emphasize that :last-child will not work if the element is not the VERY LAST element in a container.


1 Answers

Usually, your best bet is to create a negative right margin on your containing block, e.g.:

<ul>
  <li>Stuff Here</li>
  <li>Stuff Here</li>
  <li>Stuff Here</li>
  <li>Stuff Here</li>
  <li>Stuff Here</li>
  <li>Stuff Here</li>
  <li>Stuff Here</li>
</ul>

<style>
 li {
     float: left;
     width: 30%;
     margin-right: 3%;
     }
 ul {
     margin-right: -3%; /* compensate for last float %/
     }


</style>

My example is hastily written, but I'd note that the outer negative margin doesn't have to be the same. You'll have to fiddle.

Does that help?

like image 196
Jeremy Carlson Avatar answered Sep 16 '22 11:09

Jeremy Carlson