Change Styles of First/Last Elements in CSS

Sometimes it's desirable to change a style of the first and/or last elements in a container. You can do this by manually applying classes to your HTML elements: ("last-child" still not supported in IE8).

[View All Snippets]
Show Plain Text »
  1. <style type="text/css">
  2. p.first { margin-top: 0 !important; margin-left: 0 !important; }
  3. p.last { margin-bottom: 0 !important; margin-right: 0 !important; }
  4. /* or */
  5. div#articles p:first-child { border:1px solid #c1c13a; }
  6. div#articles p:last-child { border:1px solid #3ac13a; }
  7. /* or */
  8. div#articles > :first-child { text-align:left; }
  9. div#articles > :last-child { text-align:right; }
  10. </style>
  11.  
  12. <div id="articles">
  13.  <p class="first">1st article: lorem ipsum dolor sit amet...</p>
  14.  <p>2st article: lorem ipsum dolor sit amet...</p>
  15.  <p>3st article: lorem ipsum dolor sit amet...</p>
  16.  <p>4st article: lorem ipsum dolor sit amet...</p>
  17.  <p class="last">5st article: lorem ipsum dolor sit amet...</p>
  18. </div>


Result:

1st article: lorem ipsum dolor sit amet...

2st article: lorem ipsum dolor sit amet...

3st article: lorem ipsum dolor sit amet...

4st article: lorem ipsum dolor sit amet...

5st article: lorem ipsum dolor sit amet...

Create Your Free Account
Please remember that this information is essential to use our services correctly.
After creating the account you will be able to download all of our FREE products.
Fields marked with * are mandatory






Please send me information about updates, new products, specials and discounts from ApPHP!
We recommend that your password should be at least 6 characters long and should be different from your username/email. Please use only letters of the English alphabet to enter your name.

Your e-mail address must be valid. We use e-mail for communication purposes (order notifications, etc). Therefore, it is essential to provide a valid e-mail address to be able to use our services correctly.

All your private data is confidential. We will never sell, exchange or market it in any way. Please refer to Privacy Policy.

By clicking "Create Account", you are indicating that you have read and agree to the ApPHP Terms & Conditions.