Grow your CSS skills. Land your dream job.

Centering a Div Element

  • # April 6, 2008 at 4:40 am

    my first style sheet :oops: :

    Code:
    {

    margin: 0;
    padding: 0;
    border: 0;

    background-color: white;

    }

    /* Content ———————————————–*/
    div
    {
    vertical-align: middle;
    display: block;
    font-family: Georgia, serif;

    font-size: 16px;

    letter-spacing: 1px;

    padding: 20px 20px 20px 20px;
    margin: 20px 20px 20px 20px;

    background-color: white;

    border-left: 2px solid #cccccc;

    border-right: 2px solid #cccccc;

    border-top: 2px solid #cccccc;

    border-bottom: 2px solid #cccccc;

    width: 500px;
    }

    my problems are:
    – how do I align the div element to the center of the page
    – and how do I make the overflow words go to the next line

    Thanks for Helping

    # April 6, 2008 at 5:49 am

    The first question I can answer. Try this:

    div {
    width: 500px;
    margin: 0 auto;
    }

    and for old browsers, also add this:

    body {
    text-align: center;
    }

    And in beacause of the body-centering you need to add "text-align: left;" in the div to outline the text left again. About the second question, I am not sure what exactly you mean. Can you please explain what you meant?

    # April 6, 2008 at 6:25 am

    Ill try that out right now.
    About the text i meant that if i draw a border around the div element and place a realy long line of text in it the text goes over the border

    # April 6, 2008 at 7:34 am

    You could give the div a padding. That means the space between the border and the content. More about that here. Another option would be to give your paragraph a width too. Something like this:

    Code:
    div {
    width: 500px;
    border: 1px solid black;
    }

    p {
    with: 400px;
    }

    Some long text here

    # April 6, 2008 at 10:43 am

    Text, by default, should be wrapping down onto the next line automatically inside your div, you don’t need to do anything special to achieve that. The two exceptions are that somewhere else in the stylesheet "white-space" got set to "no-wrap", which prevents text from breaking down onto the next line. Or, the text doesn’t have any spaces in it. For example, really really long URL’s. Those have a habit of wanting to stick together on one line and busting outside of div’s.

    # April 7, 2008 at 5:15 am

    Thanks, it works!

    # January 14, 2009 at 4:25 pm

    Is it possible to center a div inside another div, without giving it a width?

    Example:

    Code:

    I want the navigation centered inside the header, but I don’t want to constrain the width of the nav (at least not greater than the header).

Viewing 7 posts - 1 through 7 (of 7 total)

You must be logged in to reply to this topic.

*May or may not contain any actual "CSS" or "Tricks".