简体   繁体   English

如何将锚标记置于父元素内部居中,而锚占据父空间的所有空间

[英]How to center an anchor tag inside a parent element with the anchor taking up all space of parent

So I'm trying to make an anchor element take up 100% of parent element so that the parent is all clickable and center the text vertically and horizontally inside the parent element. 因此,我试图使锚元素占据父元素的100%,以便所有父元素都可单击,并将文本在父元素内垂直和水平居中。 What would be the css to go along with the following HTML to make the above happen? 配合以下HTML进行上述操作的CSS是什么?

<ul>
    <li><a>text</a></li>
</ul>

just give it the display:block property, which will cause it to take 100% of it's parent, like so: 只需为其提供display:block属性,它将使它占据其父级的100%,如下所示:

 li { background-color:red; } a { background-color:blue; display:block; color:white; width:100%; // not actually necessary, but good practice } 
 <ul> <li><a href="#">text</a></li> </ul> 

You can add CSS display: block; 您可以添加CSS display: block; or display:table; display:table; properties to anchors for 100% width. 属性以锚定为100%宽度。

 ul{ list-style-type: none; } li{ width:80%; margin-bottom:20px; } a{ position:relative; line-height: 30px; width:100%; color:#fff; background-color: #666; display:table; padding:5px 10px; } a:hover{ opacity: 0.8; } 
 <ul> <li><a href="#">text 1</a></li> <li><a href="#">text 2</a></li> <li><a href="#">text 3</a></li> </ul> 

There are several ways you can do this. 有几种方法可以做到这一点。 It sort of depends on what CSS you have going on around it, or other things you are trying to accomplish visually. 它取决于您正在使用什么CSS,或者您想通过视觉完成的其他事情。

One thing to remember is that only the <a> itself is clickable. 要记住的一件事是,只有<a>本身是可单击的。 If you only center the anchor inside the <li> , the area around it will not be clickable—only its text will be. 如果仅将锚定居于<li> ,则将无法单击其周围的区域,而只能单击其文本。 In order to make the entire <li> behave as though it is clickable, you need to make the anchor itself fill the entire space within the <li> . 为了使整个<li> 表现得好像可以单击一样,您需要使锚点本身填充<li>内的整个空间。 Then you can center the text within the anchor. 然后,您可以将文本置于锚点的中心。

One way to do this is with flexbox: 一种方法是使用flexbox:

li {
  height: 100px; // for example, to demonstrate vertical centering
}

a {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  width: 100%;
}

Note: don't use the a selector alone here; 注意:不要使用a单独选择在这里; this is just for this code snippet. 这仅用于此代码段。 You should probably use a class instead. 您可能应该改用一个类。

FYI, the other answers provided so far don't actually center the text, and don't account for vertical centering. 仅供参考,到目前为止提供的其他答案实际上并未使文本居中,也没有考虑垂直居中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM