By utilizing the CSS properties position:relative
and position:absolute
along with transform:translate()
, you can achieve the desired layout effect.
To demonstrate this, I switched from using col-md
to col-xs
in order to better showcase the effect within the limited space of the snippet.
In addition, I included height:100%
for both columns so that they inherit the height of their parent container, resulting in the vertical and horizontal center alignment of the span
. This alignment remains consistent even when resizing the browser window.
.col-xs-10,
.col-xs-2 {
position: relative;
}
.col-xs-10 span {
position: absolute;
top: 50%;
left: 50%;
transform:translate(-50%, -50%);
}
.col-xs-2 span {
position: absolute;
top: 50%;
left: 50%;
transform:translate(-50%, -50%);
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<div class="row" style="height:200px;background-color:grey">
<div class="col-xs-10" style="background-color:red;height:100%;">
<span>How to center this vertically/horizontally</span>
</div>
<div class="col-xs-2" style="background-color:blue;height:100%;">
<span>This too</span>
</div>
</div>