使用js实现 祖先元素是宽度是500父级元素宽度是1000子元素宽度是300使子元素居中显示
HTML代码:
<div class="ancestor">
<div class="parent">
<div class="child">子元素</div>
</div>
</div>
CSS代码:
.ancestor {
width: 500px;
background-color: gray;
}
.parent {
width: 1000px;
margin: 0 auto;
background-color: lightgray;
}
.child {
width: 300px;
height: 50px;
background-color: darkgray;
}
JS代码:
const ancestorWidth = 500;
const parentWidth = 1000;
const childWidth = 300;
const ancestor = document.querySelector('.ancestor');
const parent = document.querySelector('.parent');
const child = document.querySelector('.child');
// 设置祖先元素宽度
ancestor.style.width = `${ancestorWidth}px`;
// 设置父级元素宽度和居中显示
parent.style.width = `${parentWidth}px`;
parent.style.margin = '0 auto';
// 设置子元素宽度和居中显示
child.style.width = `${childWidth}px`;
child.style.margin = '0 auto';
``
原文地址: https://www.cveoy.top/t/topic/fIst 著作权归作者所有。请勿转载和采集!