[英]Center div element containing text vertically and horizontally in another div
I know that there are many similar questions;我知道有很多类似的问题; however, I'm unable to center my example with those answers.
但是,我无法以这些答案为中心。
I have the following page structure:我有以下页面结构:
.close-button { margin-top: auto; padding: 0; cursor: pointer; border: none; border-radius: 5rem; background: black; color: white; position: relative; width: 5em; height: 5em; }.close-button.mark { position: absolute; width: 100%; height: 100%; margin: 0; top: 0; left: 0; right: 0; bottom: 0; }
<button class="close-button"> <div class="mark">+</div> </button>
I want to center the textContent of the mark div in the middle of the created circle, as you can see my attempt with position: absolute
did not work.我想将标记 div 的 textContent 居中在创建的圆圈的中间,你可以看到我对
position: absolute
did not work。 I also tried it with flex
, however, that also did not create the result I wanted to achieve.我也尝试过
flex
,但是,这也没有产生我想要达到的结果。 Furthermore, I also stumbled upon margin-collapse, but I doubt that it is the issue here.此外,我还偶然发现了margin-collapse,但我怀疑这是这里的问题。
How can I center my text vertically and horizontally in the created circle?如何在创建的圆圈中垂直和水平居中我的文本?
You can do it by adding these properties in your classes您可以通过在类中添加这些属性来做到这一点
.close-button{
display: grid;
place-items: center;
}
Before doing that, remove these properties:在此之前,请删除以下属性:
.close-button {
position: relative;
}
.close-button .mark {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
}
You can do it via flex
by applying it on the parent.您可以通过
flex
将其应用于父级来实现。 No need to apply any CSS on the child (mark)
for that matter.为此,无需在孩子
(mark)
上应用任何 CSS。
.close-button { margin-top: auto; padding: 0; cursor: pointer; border: none; border-radius: 5rem; background: black; color: white; position: relative; width: 5em; height: 5em; display: flex; justify-content: center; align-items: center; }
<button class="close-button"> <div class="mark">+</div> </button>
.close-button .mark {
display: flex;
justify-content: center;
flex-direction: column;
}
Remove position and use this删除 position 并使用这个
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.