制作<a> tag to take 100% height of inline-block parent

时间:2016-11-23 04:17:44

标签: html css

I want to make #menu a tag take up 100% of the height of its parent element. The parent element forms part of a horizontal list, so has display: inline-block set.

However, the a tag does not extend the full height of parent div, despite me setting it to display: block; height: 100%;.

See here: https://jsfiddle.net/wqec16we/12/

有人知道是否可以这样做吗?

#wrapper {
  width: 100%;
  border: 1px solid #ccc;
  overflow: auto;
  text-align: right;
}

#hi, #menu {
  display: inline-block;
  height: auto;
}

#hi {
  font-size: 28px;
}

#menu {
  height: 100%;
  width: 60px;
}

#menu a {
  display: block;
  height: 100%;
  width: 100%;
  text-align: center;
  background-color: #ccc;
}

2 个答案:

答案 0 :(得分:3)

您可以使用值添加line-height属性,例如

#menu a {
  display: block;
  height: 100%;
  width: 100%;
  text-align: center;
  background-color: #ccc;
  line-height:40px;  /*MODIFICATION*/

}

&#13;
&#13;
#wrapper {
  width: 100%;
  border: 1px solid #ccc;
  overflow: auto;
  text-align: right;
  
}

#hi, #menu {
  display: inline-block;
  height: auto;
  
}

#hi {
  font-size: 28px;
  
}

#menu {
  height: 100%;
  width: 60px;
  
}

#menu a {
  display: block;
  height: 100%;
  width: 100%;
  text-align: center;
  background-color: #ccc;
  line-height:40px; /*MODIFICATION*/
  
}
&#13;
<div id="wrapper">

<div id="hi">
HI
</div>

<div id="menu">
 <a href="#">Menu</a>
</div>

</div>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

您可以使用flexbox为已知或未知高度容器执行相等高度的列,也适用于水平和垂直居中。例如:

#wrapper {
  border: 1px solid #ccc;
  display: flex;
  justify-content: flex-end;
}
#hi {
  font-size: 28px;
  padding: 0 5px;
}
#menu {
  display: flex;
}
#menu a {
  background-color: #ccc;
  padding: 0 5px;
  flex: 1;
  display: flex;
  justify-content: center;
  align-items: center;
}
<div id="wrapper">
  <div id="hi">HI</div>
  <div id="menu">
    <a href="#">Menu</a>
  </div>
</div>

如果您不需要<div>周围的<a>,则可以更轻松。例如:

#wrapper {
  border: 1px solid #ccc;
  display: flex;
}
#hi {
  flex: 1;
  font-size: 28px;
  text-align: right;
  padding: 0 5px;
}
#menu {
  background-color: #ccc;
  padding: 0 5px;
  display: flex;
  justify-content: center;
  align-items: center;
}
<div id="wrapper">
  <div id="hi">HI</div>
  <a id="menu" href="#">Menu</a>
</div>

您还可以使用CSS表来支持旧浏览器。例如:

#wrapper {
  border: 1px solid #ccc;
  display: table;
  width: 100%;
}
#hi,
#menu {
  display: table-cell;
  vertical-align: middle;
  padding: 0 5px;
}
#hi {
  text-align: right;
  font-size: 28px;
  width: 100%;
}
#menu {
  background-color: #ccc;
  white-space: nowrap;
}
<div id="wrapper">
  <div id="hi">HI</div>
  <a id="menu" href="#">Menu</a>
</div>