Elias7
Elias7

Reputation: 12861

Centering a div both horizontally and vertically at all times on a responsive parent

I have a header that I would like to keep centered inside a parent image div both horizontally and vertically at all times when the parent div does not have a fixed width and height but instead has a responsive width and height using Twitter Bootstrap 3.1's responsive columns.

HTML:

<div id ="firstholder" class= " col-sm-4 col-md-4 col-lg-4">
    <a href="home.html" title="Home" class="imglink"> 
        <div class="item1"><h1 class="slickfont1" >Home</h1>
        </div><img src="/images/slide2.JPG" alt="City Lights Image"  class="img-responsive" >
    </a>
</div>


#firstholder {
    display:inline-block;
    float:left;
    margin:0;
    padding:0;
    height:auto;
    position:relative;
}


a.imglink  {
    background:  #fff;
    display: inline-block;
    width:100%;
    height:auto;
    position:relative;
}

.item1 {
    height:150px;
    width: 150px;
    margin: 0 auto;
    position:absolute;
    z-index:100;
    vertical-align:middle;
}

.slickfont1 {
    z-index:10;
    color: #fff;
    position:absolute;
    font-family: 'Bowlby One SC', cursive;
    font-size: 37px;
    font-weight:lighter;  
    position: absolute;
    text-shadow:0 0 0 transparent, -2px 2px 2px  #1542bd;
}

Thanks :)

Upvotes: 1

Views: 1135

Answers (2)

Bangash
Bangash

Reputation: 1172

You can use this nice method by Chris Coyier at CSS Tricks, he uses percentages and CSS3's transform:translate to achieve what you need. Centering Percentage Width/Height Elements
Now as you're using Bootstrap, so you're to tweak it for yourself.

The code from Chris Coyier:

.center {
  position: absolute;
  left: 50%;
  top: 50%;

  transform: translate(-50%, -50%);

  width: 40%;
  height: 50%;
}

Better to go to CSSTricks (using above link) and study the whole Post (you'll also find the reason of using it and why its better than other methods of centring). I hope this helped you.

Upvotes: 3

SULTAN
SULTAN

Reputation: 1159

I am not sure if I understood you right, but let's start from here:

CSS:

div.center {
  display: table-cell;
  width: 200px;
  height: 200px;
  vertical-align: middle;
  text-align: center;
    border: 1px solid #000;
    background-color: #ccc;
}

div.inner {
    margin: 0 auto;
}

HTML:

<div class="center">
    <div class="inner">
        <div class="title">
            Title Here
        </div>
    </div>
</div>

Is this what you are trying to do? assuming the gray background is an image? SAMPLE HERE

Upvotes: 1

Related Questions