.ruler {
width: 300px; /* Adjust as needed */
height: 20px;
background-color: #f0f0f0;
border: 1px solid #ccc;
position: relative;
}
.ruler::before {
content: "";
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-image: linear-gradient(to right,
transparent, transparent 9px, #ccc 9px, #ccc 10px,
transparent 10px, transparent 19px, #ccc 19px, #ccc 20px,
transparent 20px, transparent 49px, #ccc 49px, #ccc 50px,
transparent 50px, transparent 99px, #ccc 99px, #ccc 100px,
transparent 100px, transparent 299px /* Adjust based on width */
);
background-size: 100px 100%; /* Major tick every 100px */
}
.ruler::after {
content: "";
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 50%; /* Smaller ticks are half the height */
background-image: linear-gradient(to right,
transparent, transparent 4px, #ccc 4px, #ccc 5px,
transparent 5px, transparent 9px, #ccc 9px, #ccc 10px,
transparent 10px, transparent 14px, #ccc 14px, #ccc 15px,
transparent 15px, transparent 19px, #ccc 19px, #ccc 20px,
transparent 20px, transparent 24px, #ccc 24px, #ccc 25px,
transparent 25px, transparent 29px, #ccc 29px, #ccc 30px,
transparent 30px /* and so on... */
);
background-size: 10px 100%; /* Minor tick every 10px */
}
/* Number labels (optional) */
.ruler span {
position: absolute;
bottom: -20px; /* Position below the ruler */
font-size: 10px;
}
.ruler span:nth-child(1) { left: 0; content: "0"; }
.ruler span:nth-child(2) { left: 100px; content: "100"; }
.ruler span:nth-child(3) { left: 200px; content: "200"; }
.ruler span:nth-child(4) { left: 300px; content: "300"; } /* Adjust based on width and ticks */
Explanation and Improvements:
- Basic Structure: The
.ruler
class sets the basic dimensions and background. - Ticks using
linear-gradient
: The::before
and::after
pseudo-elements uselinear-gradient
to create the tick marks. This is more efficient than creating individual elements for each tick. - Major and Minor Ticks:
::before
creates the major ticks (every 100px in this example), and::after
creates the minor ticks (every 10px). Adjust thebackground-size
andlinear-gradient
values to change the tick spacing. - Number Labels (Optional): The
span
elements and their corresponding CSS provide numbered labels below the ruler. You'll need to adjust theleft
values andcontent
for eachspan
based on your ruler's length and tick intervals. This part can be generated dynamically with JavaScript for more flexibility. - Dynamic Generation with JavaScript (Recommended): For a truly flexible and reusable ruler, consider using JavaScript to dynamically generate the ticks and labels based on desired length, units, and precision. This avoids hardcoding values in CSS and makes the ruler much more adaptable.
Example JavaScript Implementation (for dynamic generation):
function createRuler(length, unit = "px", majorTick = 100, minorTick = 10) {
标签:画出,10px,content,css,background,ruler,刻度尺,transparent,ccc
From: https://www.cnblogs.com/ai888/p/18587842