[前端] 学习内容总结,css样式居中以及点击包裹a标签的容器元素也能触发a标签的点击事件
一、Css样式居中
1.1、用flex布局来使子元素居中
flex中justify-content是指定子元素在主轴上的对齐方式;align-items是子元素在交叉轴上的对齐方式。
所以我们可以通过设定这两个属性为居中来使子元素居中。
.navbar {
display: flex; //flex 布局
justify-content: center; //主轴上的对齐方式
align-items: center; //交叉轴上的对齐方式
}
1.2、设置left:0,right:0,bottom:0,margin:auto,通过自适应margin来居中。自适应margin使其符合前面的条件。
li {
position: relative;
.cursor {
position: absolute;
left: 0;
right: 0;
bottom: 0;
margin: auto;
}
}
1.3、通过移动和定位来居中
li {
position: relative;
a {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
}
二、怎么使点击包裹a标签外的容器元素也能触发a标签的点击事件
从点击事件的event对象上找到子元素触发点击事件。
<li
className={tabIndex === 1 ? "active" : ""}
onClick={(e) => {
const target = e.target as HTMLTextAreaElement; //ts写法:告知该元素是什么类型
const child = target.children[0] as HTMLElement | null;
console.log(child);
child?.click(); //子元素点击事件
//e.target.childNodes[0].click();
setTabIndex(1);
}}
>
<span>
<NavLink className="navbar-brand" to="/discovery">
发现音乐
</NavLink>
</span>
<div className={tabIndex === 1 ? "cursor triangle" : ""}></div>
</li>