Home > database >  How to use :fist-child correctly?
How to use :fist-child correctly?

Time:09-29

I have a html structure and would like to set the margin-top for the first div to 0. That is for the div that is surrounded with asterisk.

I tried to use the following css code but it does not work as required:

div:first-child {
    margin-top:0 !important;
}

as well as

a>div:first-child {
    margin-top:0 !important;
}

as well as

.l-content-width.l-content-width--narrow.l-stack.l-stack--chicken{
     div:first-child {
        margin-top:0 !important;
    }
}

here is my html:

 <div >
        <a href="https://something&lang=de"  target="_blank">
            **<div  data-products-links>**
                <strong >something</strong>
                
        <i >
            <svg viewBox="0 0 16 16" >
                <use href="#ui-arrow-right"></use>
            </svg>
        </i>
    
            </div>
        </a>
    
        <a href="https://something&lang=de"  target="_blank">
            <div  data-products-links>
                <strong >something</strong>
                
        <i >
            <svg viewBox="0 0 16 16" >
                <use href="#ui-arrow-right"></use>
            </svg>
        </i>
    
            </div>
        </a>
    
        <a href="https://something&lang=de"  target="_blank">
            <div  data-products-links>
                <strong >something</strong>
                
        <i >
            <svg viewBox="0 0 16 16" >
                <use href="#ui-arrow-right"></use>
            </svg>
        </i>
    
            </div>
        </a>
    </div>

I am able to correctly solve this using JS/TypeScript but was wondering if there is a more elegant way to do it in pure CSS?

this.productsLinks = config.element.querySelector<HTMLSelectElement>('[data-products-links]');
if (this.productsLinks.classList.contains('l-stack')) {
       this.productsLinks.classList.remove('l-stack');
}

CodePudding user response:

All the divs in the code you have provided are first children (including possibly the very first one since at minimum it will be within a body element).

It is the anchor element that is the first child so you need to select that, then this snippet selects the first direct child of the anchor element (rather than any child) as well:

.t-link-area:first-child > div.t-link-area__link:first-child {
  margin-top: 0;
}

CodePudding user response:

Thanks @Cédric for pointing me in the right direction:

a:first-child div{
  margin-top: 0!important;
}
  • Related