Anthony
Anthony

Reputation: 5433

Centering a fixed width div flanked by two variable divs

I'm trying to set up a display that has an icon centered in a div. To the left and/or right is a variable amount of text. Example:

<div class="container">
    <div class="left-text">This text is on the left</div>
    <div class="icon-cell"><div class="icon smiley-face"></div></div>
    <div class="right-text">And more text is over here...</div>
</div>

My goal would be for icon-cell to always be centered horizontally, presuming .container has a width of 100%.

I was using a table for a little while, but it wasn't possible to do:

<td style="width:50%"></td>
<td style="width:48px"></td>
<td style="width:50%"></td>

Any ideas on how to do this without using Javascript?

CodePen

Upvotes: 0

Views: 295

Answers (6)

TwoD
TwoD

Reputation: 315

I suppose I'm a bit late to the party, but this can also be done using display: table-cell;. Large amounts of texts should wrap rather than push the icon around and if you want padding for the "cells" you won't need to compensate for the width of the centered icon.

.container {
  background: #eee;
  display: table-row;
}

.container > div {
  display: table-cell;
  vertical-align: top;
  width: 50%;
}

.container > .icon-cell {
  min-width: 50px;
  width: 50px;
}

.container > .icon-cell img {
  width: 100%;
  height: auto;
}

http://jsfiddle.net/Ljho1nx9/2/

Upvotes: 0

DevlshOne
DevlshOne

Reputation: 8457

This gives you a clean newspaper kind of look.....

.container {
  width: 100%;
  height: 300px;
}
.left-text {
  position:absolute;
  background: rgba(0, 255, 0, .2);
  margin-left:0px;
  top:0px;
  padding-right:350px;
  text-align:justify;
  text-justify:auto;
}
.right-text {
  position:absolute;
  background: rgba(0, 0, 255, .2);
  margin-right:0px;
  top:0px;
  padding-left:350px;
  text-align:justify;
  text-justify:auto;
}
.icon.smiley-face {
  background: url(//placehold.it/48/48/00ff00);
  height: 48px;
  width: 48px;
  margin:0px auto;
}

Upvotes: 1

nirazul
nirazul

Reputation: 3955

You could use display: inline-block for the divs in conjunction with text-align: center:

.container {
    width: 100%;
    background: #eee;
    text-align: center;
}

.container > div {
    display: inline-block;
}

.container > .icon-cell {
    width: 50px;
}

Example

There will occur problems, when you insert more text. Then you need to fix the width of your container-elements and eliminiate white-space between inline-blocks (I use font-size: 0). Here's another example:

More Text

Upvotes: 2

123
123

Reputation: 525

You can just use margins and display: inline-block; in css

Upvotes: 0

123
123

Reputation: 525

Use css float and align. CSS: .left-text { float: left; } .right-text { float: right; } .icon-cell { text-align: center; } .container { display: inline-block; }

Upvotes: 0

RbG
RbG

Reputation: 3213

this trick may work

.icon{
  width:100px;
  margin:0 auto;
}

Upvotes: 0

Related Questions