中心跨度垂直

时间:2016-02-09 09:39:17

标签: css

我有这段代码:

a {
  background: #A9A9A9;
  display: block;
  position: absolute;
  right: 0;
  top: 0;
  height: 100%;
  width: 20%;
  vertical-align: middle;
  float: right;
  text-align: center;
}
a span {
  display: inline-block;
  vertical-align: middle;
}
<a href="#"><span>Center</span></a>

我想将span垂直居中到a中的position: absolute;

4 个答案:

答案 0 :(得分:3)

使用position:relative来跨越top:50%

a {
	background: #A9A9A9;
	display: block;
    position: absolute;
    right: 0;
    top: 0;
    height: 100%;
    width: 20%;
    vertical-align: middle;
	float: right;
	text-align: center;
}

a span {
    display: inline-block;
    position: relative;
    top: 50%;
    transform: translate(0px, -50%);
}
<a href="#"><span>Center</span></a>

解决方案2:

使用display:tabledisplay:table-cell

a {
  background: #A9A9A9;
  display: block;
  position: absolute;
  right: 0;
  top: 0;
  height: 100%;
  width: 20%;
  vertical-align: middle;
  float: right;
  text-align: center;
  display:table;
}
a span {
  display: table-cell;
  vertical-align: middle;
}
<a href="#"><span>Center</span></a>

答案 1 :(得分:1)

Flexbox的大用途。只需确保检查供应商前缀和broswer支持:

https://css-tricks.com/snippets/css/a-guide-to-flexbox/

a {
	background: #A9A9A9;
	display: flex;
    justify-content: center;
    align-items: center;
    position: absolute;
    right: 0;
    top: 0;
    height: 100%;
    width: 50%;
}

a span {
  
}
<a href="#"><span>Center</span></a>

答案 2 :(得分:0)

a {
	background: #A9A9A9;
	display: block;
    position: absolute;
    right: 0;
    top: 0;
    height: 100%;
    width: 20%;
    vertical-align: middle;
	float: right;
	text-align: center;
}

a span {
    position: absolute;
    margin: auto;
    left: 0;
    right: 0;
    top: 50%;
    bottom: 0;
    height: 16px;
    margin-top: -8px; /* height/2 */ 
}
<a href="#"><span>Center</span></a>

答案 3 :(得分:0)

风格的变化可能对你有帮助

 a {
    background: #A9A9A9;
    display: table;
    position: absolute;
    right: 0;
    top: 0;
    height: 100%;
    width: 20%;
    vertical-align: middle;
    float: right;
    text-align: center;
}

a span {
    display: table-cell;
    vertical-align: middle;
}
<a href="#"><span>Center</span></a>