treehouse : what would you like to learn today?
Web Design Web Development iOS Development

Centering a Div Element

  • my first style sheet :oops: :


    {

    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
  • 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?
  • 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
  • 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:


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

    p {
    with: 400px;
    }

    <div>
    <p>Some long text here</p>
    </div>
  • 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.
  • Thanks, it works!
  • Is it possible to center a div inside another div, without giving it a width?

    Example:

    <div id=\"header\">
    <div id=\"nav\"></div>
    </div>


    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).