How to Make Content in the Middle With CSS

There is no set way to tell a browser to center a part of your Web page. You can center align text, but this is not the same as centering a box or placing a regular, left-aligned paragraph within the center of a page. In order to center content in the middle of some part of the page, you need to give a width and automatic left and right margins to that content's element. To make the centering backwards compatible with older Internet Explorer versions, you also need to adjust text alignment settings.

Instructions

    • 1

      Open your Web page in an editor or Notepad and find the content you want to center. Find out what tags wrap around the content:

      <p id=”mytext”>Paragraph text here...</p>

      Get the ID of the tags or add one as shown, using a name that is unique and easy to remember.

    • 2

      Get the tags of the content's parent element. The parent is an element that contains one or more nested “child” elements, such as a div – parent – with many paragraphs:

      <div id=”container”>
      <p id=”mytext”>Paragraph text here...</p>
      </div>

      In this example, “container” is the parent and “mytext” is the child. You need the ID of both of these elements.

    • 3

      Open the stylesheet for your Web page. If you do not already have an external stylesheet made for your Web pages, add CSS between “<style>” tags in the head of your HTML code:

      <style type=”text/css”>
      </style>

    • 4

      Create a style rule for the element you want to center. Give this element “auto” left and right margins. The element also needs a width, either in pixels like “50px” or a percentage such as “50%.” In most browsers, this will cause the content to center within its parent element:

      #mytext {
      margin-left: auto;
      margin-right: auto;
      width: 300px;
      }

    • 5

      Write a style rule for the parent element and set its text alignment property to “center.” Some older versions of Internet Explorer require this setting. When using this trick, however, you must set each child element's text alignment back to normal, unless you want text within those elements centered as well:

      #container {
      text-align: center;
      }
      #mytext {
      margin-left: auto;
      margin-right: auto;
      width: 300px;
      text-align: left;
      }

Related Searches:

Comments

Related Ads

Featured