user1943020
user1943020

Reputation:

How can I center text inside a div with the same space to the left and right?

I have an H1 element inside a DIV inside a header:

<header class="container_12">
   <div class="grid_3">
       <h1><b>xx</b></h1>
   </div>
</header>

and the following CSS:

.container_12 .grid_3 {
    width: 23%;
}
.grid_1, .grid_2, .grid_3, .grid_4, .grid_5, .grid_6, .grid_7, .grid_8, .grid_9, .grid_10, .grid_11, .grid_12 {
    display: inline;
    float: left;
    margin-left: 0.99%;
    margin-right: 0.99%;
}
header h1 {
    margin:0 auto; 
text-align:center;
    display: inline;
    line-height: 77px;
    color: #ddd;
    font-size: 4em;
    font-family: "Segoe UI Web Light", "Segoe UI Light", "Segoe UI Web Regular", "Segoe UI", "Segoe UI Symbol", "Helvetica Neue", Arial;
}

I am looking for some advice. I would like to position the "xx" text in the middle of the grid_3 with the same amount of space to the left right and left of the "xx".

Upvotes: 0

Views: 101

Answers (4)

Nick Fury
Nick Fury

Reputation: 1313

You can either do:

  1. text-align: center;

https://developer.mozilla.org/en-US/docs/CSS/text-align

  1. margin: 0 auto;

https://developer.mozilla.org/en-US/docs/CSS/margin

 .container_12 .grid_3 {
    width: 23%;
 }

 .container_12 > .grid_3 > h1 {
    text-align: center
 }

A jsfiddle for your current example: http://jsfiddle.net/bxG27/

Upvotes: 2

James Donnelly
James Donnelly

Reputation: 128856

h1 {
    text-align:center;
    line-height: 77px;
    color: #ddd;
    font-size: 4em;
    font-family: "Segoe UI Web Light", "Segoe UI Light", "Segoe UI Web Regular", "Segoe UI", "Segoe UI Symbol", "Helvetica Neue", Arial;
}

JSFiddle. I've given the heading a dark background so you can easily see that the text is centrally aligned. As I mentioned in my comment on your post, display:inline; on your h1 is what's causing it to fail for you, as widths are not applied to inline elements.

Upvotes: 0

Kyuuji
Kyuuji

Reputation: 744

You need:

text-align:center;

Should do the trick, applied to the h1.

Here's a fiddle:

http://jsfiddle.net/qGaCY/1/

Upvotes: 2

Tepken Vannkorn
Tepken Vannkorn

Reputation: 9723

.grid_3 {
    text-align: center;
}

NOTE: <b>..</b> is deprecated in HTML5. Use <strong>..</strong> instead.

Upvotes: 2

Related Questions