SomeCode SomeCode - 3 months ago 15
CSS Question

Vertical align conflicts with border box

I want to say that I've tried everything, but I refuse to believe that's true. I'm trying to vertical-align an image inside a div. Although it looked like it worked, I noticed there was more space above the image than below.

After some debugging, I found that

box-sizing: border-box
was the problem. But because I'm using Bootstrap (and it seems it relies on it), I can't change it.

See my snippet below. Click 'Toggle box-sizing' to turn box-sizing on or off.



var toggled = false;
$('#toggle').on('click', function() {
if (!toggled) {
$('*').css('box-sizing', 'border-box');
toggled = true;
} else {
$('*').css('box-sizing', 'initial');
toggled = false;
}
});

.left-sidebar {
width: 180px;
background-color: #34495e;
}
.left-sidebar .user-menu {
height: 80px;
position: relative;
padding: 0 15px;
color: #fff;
line-height: 80px;
border-bottom: 2px solid #3d566e;
}
.left-sidebar .user-menu img {
vertical-align: middle;
border-radius: 50%;
}
.left-sidebar .user-menu .user-info {
margin-left: 5px;
font-size: 16px;
font-weight: 300;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button id="toggle">Toggle box-sizing</button>

<nav class="left-sidebar">
<div class="user-menu">
<img src="https://placehold.it/50x50">
<span class="user-info">Someone</span>
</div>
</nav>
<!-- .left-sidebar -->





I hope you guys can help me out.

Answer

Not sure if you can use flexbox but here's a way to keep it centered.

var toggled = false;
$('#toggle').on('click', function() {
		if (!toggled) {
    		$('*').css('box-sizing', 'border-box');
        toggled = true;
    } else {
    		$('*').css('box-sizing', 'initial');
        toggled = false;
    }
});
.left-sidebar {
    width: 180px;
    background-color: #34495e;
}
.left-sidebar .user-menu {
    display: flex; /* added */
    align-items: center; /* added */
    /* height: 80px; || removed */
    line-height: 80px; /* kept */
    /* position: relative; || removed */
    padding: 0 15px;
    color: #fff;
    border-bottom: 2px solid #3d566e;
    padding-top: 4px; /* added to negate border-bottom */
}
.left-sidebar .user-menu img {
    /* vertical-align: middle; || removed */
    border-radius: 50%;
}
.left-sidebar .user-menu .user-info {
    margin-left: 5px;
    font-size: 16px;
    font-weight: 300;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<button id="toggle">Toggle box-sizing</button>

<nav class="left-sidebar">
    <div class="user-menu">
        <img src="https://placehold.it/50x50">
        <span class="user-info">Someone</span>
    </div>
</nav>
<!-- .left-sidebar -->

fiddle

https://jsfiddle.net/Hastig/efoyyms4/7/