Here are 4 responsive solutions implemented in pure Less, all packaged into reusable methods.
Solution 1: Mixed packaging of basic equipment
// Define device breakpoint variable
@mobile-max: 767px;
@tablet-min: 768px;
@tablet-max: 1024px;
@desktop-min: 1025px;
// Equipment mix
.mobile(@rules) {
@media (max-width: @mobile-max) {
@rules();
}
}
.tablet(@rules) {
@media (min-width: @tablet-min) and (max-width: @tablet-max) {
@rules();
}
}
.desktop(@rules) {
@media (min-width: @desktop-min) {
@rules();
}
}
// Use example
.header {
font-size: 16px;
.mobile({
font-size: 14px;
padding: 8px;
});
.tablet({
font-size: 15px;
padding: 12px;
});
.desktop({
font-size: 18px;
padding: 20px;
});
}
Solution 2: Parameterized device query
// Parameterized mixing
.device(@type, @rules) {
& when (@type = mobile) {
@media (max-width: 767px) { @rules(); }
}
& when (@type = tablet) {
@media (min-width: 768px) and (max-width: 1024px) { @rules(); }
}
& when (@type = desktop) {
@media (min-width: 1025px) { @rules(); }
}
}
// Use example
.navbar {
height: 40px;
.device(mobile, {
height: auto;
flex-direction: column;
});
.device(tablet, {
height: 50px;
padding: 0 15px;
});
}
Solution 3: Configurable breakpoint mixing
// Universal responsive hybrid
.responsive(@min, @max, @rules) {
& when not (@min = 0) and not (@max = 0) {
@media (min-width: @min) and (max-width: @max) { @rules(); }
}
& when (@min = 0) {
@media (max-width: @max) { @rules(); }
}
& when (@max = 0) {
@media (min-width: @min) { @rules(); }
}
}
// Use example
.card {
width: 100%;
// cell phone
.responsive(0, 767px, {
margin: 5px;
});
// Tablet
.responsive(768px, 1024px, {
width: 48%;
margin: 8px;
});
// PC
.responsive(1025px, 0, {
width: 23%;
margin: 10px;
});
}
Solution 4: Equipment Direction Enhanced Version
// With equipment direction detection
.orientation(@device, @dir, @rules) {
& when (@device = mobile) and (@dir = portrait) {
@media (max-width: 767px) and (orientation: portrait) { @rules(); }
}
& when (@device = mobile) and (@dir = landscape) {
@media (max-width: 767px) and (orientation: landscape) { @rules(); }
}
& when (@device = tablet) {
@media (min-width: 768px) and (max-width: 1024px) { @rules(); }
}
}
// Use example
.gallery {
grid-template-columns: 1fr;
.orientation(mobile, landscape, {
grid-template-columns: repeat(2, 1fr);
});
.orientation(tablet, _, {
grid-template-columns: repeat(3, 1fr);
});
}
Solution selection suggestions:
- Basic mixing: suitable for clear three-stage breakpoint requirements
- Parameterized mixing: Used when you need to dynamically select the device type
- Configurable breakpoints: suitable for projects that require flexible adjustment of breakpoints
- Direction enhancement: Used when handling horizontal and vertical screen differences