Home > Enterprise >  Is there a way to center any element with HTML alone?
Is there a way to center any element with HTML alone?

Time:03-26

I'm fairly new to HTML and CSS, and basically web-development in general, but I still want to know if there is a way to center any type of element in HTML.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <h1>This is a header</h1>
    <span>This is a span element</span>
    <div><p>This paragraph is in a div element</p></div>
</body>
</html>

Is there a way to center all of this without using CSS?

CodePudding user response:

All ways of centering content without using CSS have been deprecated a long time ago (in 1999), already in the previous version of HTML which was 4.01, for example the two ways that have been suggested in other answers:

  • The align attribute, e.g.: <div align="center">...</div>
  • The <center>...</center> element

The basic idea of deprecating these things is that it is not HTML's job to determine presentational aspects of the document; HTML describes the structural aspects.

CSS describes the presentational aspects; to connect both, you have CSS classes along with the universal class attribute in HTML at your disposal, but that is only one way.

CSS also offers many different types of selectors, among those you also have selectors at your disposal that describe the hierarchic structure of the elements to which the declarations should apply; and some CSS properties, e.g. text-align affect descendant elements too, via CSS inheritance.

See this example:

body { text-align: center }
<h1>This is a header</h1>
<span>This is a span element</span>
<div>
  <p>This paragraph is in a div element</p>
</div>

CodePudding user response:

Use the center tag

  <center> 
  </center>

Inside which we can place tags and other content of the BODY to get center aligned Like this

  <center> 
      <h2>HELLO WORLD! </h2>
  </center>
  • Related