Js实现对齐
文本对齐方法
使用CSS的text-align属性控制文本对齐方式。通过JavaScript动态修改元素的style.textAlign属性实现对齐切换。
const element = document.getElementById('target');
element.style.textAlign = 'left'; // 左对齐
element.style.textAlign = 'center'; // 居中对齐
element.style.textAlign = 'right'; // 右对齐
元素居中对齐
通过设置CSS的display: flex和justify-content属性实现水平居中,结合align-items实现垂直居中。JavaScript动态添加类名或样式:

const container = document.getElementById('container');
container.style.display = 'flex';
container.style.justifyContent = 'center';
container.style.alignItems = 'center';
表格列对齐
针对表格列数据,使用text-align对齐文本,或通过vertical-align调整垂直对齐。

const tableCells = document.querySelectorAll('td');
tableCells.forEach(cell => {
cell.style.textAlign = 'right'; // 右对齐数字列
cell.style.verticalAlign = 'middle';
});
响应式对齐
结合媒体查询和JavaScript监听窗口大小,动态调整对齐方式:
window.addEventListener('resize', () => {
const element = document.getElementById('responsive');
element.style.textAlign = window.innerWidth > 768 ? 'left' : 'center';
});
绝对定位对齐
通过position: absolute和transform实现精准对齐,适用于弹出层或浮动元素:
const popup = document.getElementById('popup');
popup.style.position = 'absolute';
popup.style.left = '50%';
popup.style.top = '50%';
popup.style.transform = 'translate(-50%, -50%)';





