djames
djames

Reputation: 49

How to accurately position divs with css

I'm sure this is super simple, but I'm new to css. I'm essentially trying to position some rendered typography and make it stay centred no matter what the size of the browser is. I've tried using margins with percents, but that doesn't seem to work.

Here's my code.

html

<div class="weare">
    <img src="image/textrenders/weare.png" />
</div>
<div class="shaftesburytv">
    <img src="image/textrenders/Shaftesburytv.png" />
</div>
<div class="awebbasedstudio">
    <img src="image/textrenders/awebbasedstudio.png" />
</div>

css

.weare {}

.shaftesburytv {}

.awebbasedstudio {}

I want the result to look something like this

Any help would be appreciated.

Upvotes: 0

Views: 339

Answers (3)

Milche Patern
Milche Patern

Reputation: 20482

It can be verry simple.

If you do not split your image and gather all text of it into one.

html

<img id="my-whole-image" src="http://placekitten.com/300/250" />

css

#my-whole-image {
    margin-left:-150px;
    margin-top:-125px;
    left:50%;
    position:absolute;
    top:50%;
    display:block;
}

jsFiddled here

Just a tip, ence you're saying you are new to css, i presume you are new to html too : always use the minimum required to build your webpages. Those 3 images had to be merged into one for many reasons like server request, bandwidth, browser redraw, dom elements number.

Upvotes: 0

Niels Keurentjes
Niels Keurentjes

Reputation: 41968

Simplify your content:

<div id="container">
    <img src="http://placekitten.com/200/50">
    <img src="http://placekitten.com/300/100">
    <img src="http://placekitten.com/250/75">
</div>

Then ensure the container has the same width as the largest contained image, and apply margin:0 auto; to it to center. Finally put display:block on the images to make them all stack vertically:

#container {
    margin:100px auto;
    width:300px;
}
#container img {
    display:block;
}

Sample here.

Alternatively, if you also want to center vertically, you can also use absolute positioning and then negative margins on the absolute size of the object - no problem for you since the image sizes are fixed:

#container {
    margin-left:-150px;
    margin-top:-112px;
    left:50%;
    position:absolute;
    top:50%;
}
#container img {
    display:block;
}

Sample of this approach here.

Upvotes: 3

Abraham Hamidi
Abraham Hamidi

Reputation: 13809

Since you're using images, you could

margin: 0 auto;

to them. For text, you could

text-align:center;

With divs, you could also center align them (in HTML).

You could also use center tags: http://jsfiddle.net/A33J2/

Upvotes: 1

Related Questions