Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

center one div inside of another div - align the centers

Tags:

css

I am creating a tab with rotated text - I'm trying to center one div inside another, however I want the centers of the divs to be aligned but I'm getting alignment issues:

<div class="tileStrip" style="position:relative;width:100%;height:185px;background:#DDDDDD;">
    <div class ="clickToSlide" style="position:absolute;height:100%;width:30px;background:#AAAAAA">
     <div style="position:relative;top:50%">    
       <span style="    font-weight:bold;color:white;-webkit-transform: rotate(-90deg); -moz-transform: rotate(-90deg);display:block;">International</span>
    </div>
    </div>
</div>

how can I center one div inside a larger parent div vertically so that my rotated text is centered?

like image 355
afshin Avatar asked Jul 08 '11 23:07

afshin


1 Answers

Transformations rotate elements by their center point, so you need to position the center of your <span> to the center of your sidebar before the transformations.

First of all, you don't need the top:50% wrapper div, you can do it all on the span.

  • Before the transformations and any additional styles, your span will appear in the top left corner of your sidebar.

  • Add width:500px. In order to accurately position the center, the span must be fixed width, say 500px. We assume no text will ever be longer than that.

  • Add text-align:center. Now the text is correctly centered in our fixed width span, although the span itself is in the wrong position.

  • Add position:relative, so we can tweak the position of the span relative to its original position.

  • Add top:50% and margin-top:-10px. As 50% sets the top edge, we need to compensate with a negative top margin to center the span vertically. 10px is half of the span's height.

  • Add left:50% and margin-left:-250px, same as above, centers the span horizontally. 250px is half of the span's fixed width.

  • Finally add your transformations, and it should be properly centered.

Resulting HTML:

<div class="tileStrip" style="position:relative;width:100%;height:185px;background:#DDDDDD;">
    <div class ="clickToSlide" style="position:absolute;height:100%;width:30px;background:#AAAAAA">
       <span style="font-weight:bold;color:white;display:block;text-align:center;width:500px;position:relative;top:50%;margin-top:-10px;left:50%;margin-left:-250px;-webkit-transform: rotate(-90deg);-moz-transform: rotate(-90deg);">International</span>
    </div>
</div>

Demo: http://jsfiddle.net/jHrEm/7/

like image 94
DarthJDG Avatar answered Oct 13 '22 00:10

DarthJDG