自定义YouTube按钮与原生图标对齐问题求助
Hey there! I totally get how frustrating it is when your custom button doesn’t line up with YouTube’s native controls—nothing breaks the clean look of the player like a misaligned element. Let’s walk through fixing this together.
Looking at your code, you’ve already added the ytp-button class which is a great start, but YouTube’s native controls have some subtle layout styles that your button is missing. Here’s what we need to adjust:
- Remove duplicate styles: You’ve set
marginLefttwice—we can clean that up to avoid confusion. - Match native layout behavior: YouTube’s buttons use flexbox to center their content vertically and horizontally, so we’ll add those properties to keep things aligned.
- Tweak padding and sizing: The default padding and font size in your code might be throwing off the alignment; let’s adjust them to match the native buttons’ proportions.
- Ensure transparent background/border: Native YouTube buttons don’t have visible borders or backgrounds, so we’ll explicitly set those to match the player’s style.
Here’s the revised code with these fixes:
const button = document.createElement('button'); button.id = 'custom-speed-button'; button.textContent = `${customSpeed}x`; button.className = 'ytp-button'; // Match native button's flex layout for centered content button.style.display = 'inline-flex'; button.style.alignItems = 'center'; button.style.justifyContent = 'center'; // Adjust sizing to fit seamlessly with native controls button.style.fontSize = '14px'; button.style.fontWeight = 'bold'; button.style.padding = '0 6px'; // Match native button's appearance button.style.color = '#fff'; button.style.background = 'transparent'; button.style.border = 'none'; button.style.marginLeft = '10px'; // Ensure vertical alignment with adjacent buttons button.style.verticalAlign = 'middle';
If it still doesn’t line up perfectly, try right-clicking on one of YouTube’s native buttons (like the play button) and inspect it with your browser’s dev tools. Check the padding, height, line-height, and display properties—you can copy those values directly to your custom button to get a pixel-perfect match.
Hope this gets your button looking right at home with the rest of the controls!
内容来源于stack exchange

