FloatLeft
FloatLeft

Reputation: 1337

center a fixed width div within a percentage width div

How do I horizontally center a fixed-width div within a percentage-width div?

For example in this fiddle, I'd like the Google logo centered.

<div class="box">
    <div class="image">
      <img src="http://www.google.co.uk/intl/en_ALL/images/srpr/logo11w.png" />
    </div>
    <div class="text">Hello</div>
</div>

.box {
border-radius: 4px;
width: 30%;
margin-right: 2%;
margin-top: 10px;
background: #fff;
float: left;
position: relative;
overflow: hidden;
border: 1px solid #bdc9dc;
height: 200px;
}

.box .image {
height: 160px;
width: 400px;
background-color: #ff1769;
}

http://jsfiddle.net/FloatLeft/g2u4E/

I've looked at various 'solutions' online and I haven't found anything that worked.

Upvotes: 0

Views: 289

Answers (4)

Prasanth K C
Prasanth K C

Reputation: 7332

A div with fixed or % width can be aligned to center of its parent container by applying

margin:0 auto;

For Eg:

#divToCenter{
  height: 160px;
  width: 400px;
  margin:0 auto;
}

Upvotes: 0

Ankit Agrawal
Ankit Agrawal

Reputation: 6124

<style>
.box {
border-radius: 4px;
width: 30%;
margin-right: 2%;
margin-top: 10px;
background: #fff;
float: left;
position: relative;
overflow: hidden;
border: 1px solid #bdc9dc;
height: 200px;
}

.box .image {
height: 160px;
width: 400px;
background-color: #ff1769;
margin:auto;
}

.box .image img{
height: 100%;
width: 100%;
}
</style>

Upvotes: 1

David Nguyen
David Nguyen

Reputation: 8508

I would do this:

.box .image {
    height: 160px;
    width: 100%;
    background-color:#ff1769;
    background-position:center center; 
}

Add the image as a background image.

http://jsfiddle.net/g2u4E/5/

Upvotes: 1

Muath
Muath

Reputation: 4417

you can center the logo easy by setting background image for the div and change the background size as you need :

.box .image {
   height: 160px;
   width:400px;
   background-color:#ff1769;
   background-image: url('http://www.google.co.uk/intl/en_ALL/images/srpr/logo11w.png');
   background-size:47% 100%;
}

see FIDDLE

Upvotes: 1

Related Questions