Css/jquery implementation removes the spacing between the last and first elements in the HTML (margin)

Source: Internet
Author: User

Add Class Manually

Sometimes, we need to remove the spacing (margin) attribute of the last and first elements in a list element, and you can manually set CSS styles for them:

. margin-top:0!important margin-left:0!important;
. Last {margin-bottom:0!important; margin-right:0!important;}

Top/bottom zeroing is a useful overlay layout technique, left/right for horizontal layouts, but this approach relies on the need to manually add CSS styles to HTML tags, and if it's dynamically generated elements, it's very cumbersome to set up. Pseudo-class selectors may be a better way to choose.

Pseudo class

The following CSS selection passes: First-child and: Last-child selects the first and last elements, and then sets the style we need.
* >: first-child {margin-top:0!important; margin-left:0!important;}
* >: last-child {margin-bottom:0!important; margin-right:0!important;}

You may need to replace * for specific element tags to meet your project requirements.
Index linear elements
If we have a list of pictures, 3 rows and 3 columns, and need to remove the right spacing of the third, sixth, and nineth elements, the nth-child pseudo selector can help us:

* >: Nth-child (3n+3) {margin-right:0;}

Where the equation, 3N + 3, works like this:

(3x0) + 3 = 3
(3x1) + 3 = 6
(3x2) + 3 = 9

Jquery

jquery uses the CSS3 selector, which includes:: First-child,: Last-child, And:nth-child (). This means that in the no or browser does not fully support these choices, they will work in jquery, so you can use JavaScript support instead of CSS support. For example:
$ ("* >: Nth-child (3n+3)"). CSS ("Margin-right", 0);

Support for browsers

: First-child And:last-child works in the latest version of all major browsers, but not in IE 6. : First-child is in IE 7 + support. : Nth-child can work on safari 3, Firefox 3.5 and Chrome 1 +, but can't work in IE8.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.