TheRealPapa TheRealPapa - 5 months ago 12
CSS Question

Center image in row with floated element

I am working with

bootstrap 3
and want to center a logo on a page, but also include a button to its right. The logo should center across the page, and disregard the button's width.

I have achieved this with
JS
but i want a pure
CSS
solution. I am using
LESS
if this helps.



$(document).ready(function() {
var logo = $('.logo img');
var pdfBtn = $('#pdf-button');
var win = $(window);

var alignlogo = function() {
var pdfBtnWidth = pdfBtn.outerWidth();
logo.css({
'position': 'relative',
'left': pdfBtnWidth / 2
})
};

win.on('load resize orientationchange', alignlogo);
});

.transaction-head {
text-align: center;
}
.transaction-head-logo {
max-width: 200px;
max-height: 50px;
margin-bottom: 20px;
@media screen and (min-width: @screen-sm) {
max-width: 300px;
max-height: 75px;
}
}

<script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ=" crossorigin="anonymous"></script>
<div class="transaction-head">
<div class="top-block clearfix">
<a id="pdf-button" class="btn btn-primary pull-right" href="/url/to/generate/pdf" target="_new">
Download PDF
</a>
<div class="logo">
<img class="transaction-head-logo" src="url/to/logo">
</div>
</div>
</div>




Answer

You can following apply css on your logo to make it in center horizontally and without being affected by button width:

.logo {
  transform: translateX(-50%);
  position: absolute;
  left: 50%:
}

.transaction-head {
  text-align: center;
  padding: 10px;
}

.transaction-head .logo {
  transform: translateX(-50%);
  position: absolute;
  width: 200px;
  height: 50px;
  left: 50%;
}
@media screen and (min-width: @screen-sm) {
  width: 300px;
  height: 75px;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>
<div class="transaction-head">
    <div class="top-block clearfix">
        <a id="pdf-button" class="btn btn-primary pull-right" href="/url/to/generate/pdf" target="_new">
            Download PDF
        </a>
        <div class="logo">
            <img class="transaction-head-logo" src="url/to/logo">
        </div>
    </div>
</div>

Comments