The Hung The Hung - 4 months ago 7
HTML Question

Use ampersand to targets parent selectors

I read a few of the ampersand topics but I can't find solution for my issue. This is the output CSS I'm trying to achieve:

CSS

.box-item__info--normal,
.box-item__info--left {
padding-left: 11px;
padding-right: 11px;
}
.box-item__info--normal h4,
.box-item__info--left h4 {
font-size: 1.5em;
}
.box-item__info--normal .item-price {
float: right;
}


Then, I write this LESS syntax:

.box-item{
&__info{
position: relative;
padding: 35px 0 15px 0;

&--normal, &--left{
padding-left: 11px;
padding-right: 11px;

h4{
font-size: @delta;
}

& , & .item-price{
float: right;
}
}

&--left{
padding-top: 20px;

h4{
margin-bottom: 10px;
}
}
}
}


Will produce:

.box-item__info--normal,
.box-item__info--left {
padding-left: 11px;
padding-right: 11px;
}
.box-item__info--normal h4,
.box-item__info--left h4 {
font-size: 1.5em;
}
.box-item__info--normal,
.box-item__info--left,
.box-item__info--normal .item-price,
.box-item__info--left .item-price {
float: right;
}


Can you give any advice to make this code works as I expected, I only know the plug and comma sign to target parent selector.

Answer

This Less code will achieve what you are looking for:

.box-item{
    &__info{

        &--normal, &--left{
            padding-left: 11px;
            padding-right: 11px;

            h4{
                font-size: 1.5em;
            }
        }

        &--normal{
            & .item-price{
                float: right;
            }
        }
    }
}

You cannot achieve the last rule using the double rule &--normal, &--left{..}, because this would affect .box-item__info--left .item-price too

Comments