search
HomeWeb Front-endHTML TutorialIntroduction to the method of setting the center in html (code)

The content of this article is about the introduction (code) of the centering setting method in HTML. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Horizontal centering

In the actual development process, we will encounter many situations where elements need to be horizontally centered, such as article titles, etc. Common horizontal centering situations here include inline elements and block-level elements. Block-level elements are further divided into fixed-width block-level elements and variable-width block-level elements. Fixed-width block-level elements, as the name suggests, mean that the width of block-level elements is a fixed value; then, for variable-width block-level elements, we know that the width of block-level elements is not a fixed value.

Inline elements

When the element being set is an inline element such as text or picture, we do this by setting text-align:center to the parent element .

<body>
    <div class="textCenter">这是一个在父元素中居中元素</div>
</body>
<style>
    textCenter{
    text-align:center;
    }
</style>

It can be seen from the above code that "This is a centered element in the parent element". The CSS style of the parent element of this text adds the text-align:center; attribute, so the text is displayed in the center. However, this method is not applicable when the element to be set is a block-level element. Block-level elements are divided into two types: fixed-width block-level elements and variable-width block-level elements.

Fixed-width block-level elements

To meet the two conditions of "fixed-width" and "block-level elements" for fixed-width block-level elements, you can set the left and right margin values For auto to achieve centering.

<body>
    <div>水平居中的定宽块级元素</div>
</body>
<style>
    div{
        border:1px solid blue;
        width:100px;    /*宽度设置固定值*/
        margin:10px auto;
    }
</style>
/*或者也可以写成 margin-left:auto;
               margin-right:auto;*/
/* 元素的上下margin属性可以照常设置,不受影响 */

Variable-width block-level elements

There are three ways to center variable-width block-level elements: the first is to add the table tag; the second is to set the display: The inline method is similar to the first method. The display type is set to inline elements and the attributes of the variable-width elements are set. The third method is to set position:relative and left:50%, and use relative positioning to shift the element to the left. Move 50% to achieve centering.

Add table tag

Joining table tag takes advantage of the length adaptability of table tag (its length is not defined and the length of the parent element body is not defaulted. The length of table is Determined according to the length of the inner text), it can be regarded as a fixed-width block-level element, and then use the margin method of the fixed-width block-level element to center it horizontally.

The first step to use is to add a table tag outside the element that needs to be centered, and then set "left and right margins to be centered" for the table

<div>
    <table>
        <tbody>
            <tr><td>
            <ul>
                <li>锄禾日当午</li>
                <li>汗滴禾下土</li>
                <li>谁知盘中餐</li>
                <li>粒粒皆辛苦</li>
            </ul>
            </td></tr>
        </tbody>
    </table>
</div>
<style>
    table{
    border:1px solid;
    margin:0 auto;
    }
</style>

Set the display:inline method

Change the display of block-level elements to inline type, set it to display inline elements, and then use text-align:center to achieve centered display. The advantage of this method compared to the table method is that there is no need to add unsemantic tags, but this method also has certain problems, that is, it changes the display of block elements to inline, and the elements will be less visible after they become inline elements. Function usage.

<body>
    <div class="container">
        <ul>
            <li><a href="#">First</a></li>
            <li><a href="#">Second</a></li>
            <li><a href="#">Third</a></li>
        </ul>
    </div>
</body>
 
<style>
.container{
    text_align:center;
}
.container ul{
    list-style:none;
    margin:0;
    padding:0;
    display:inline;
}
 
.container li{
margin-right:10px;
display:inline;
}
</style>

Set position:relative and left:50%

By setting float to the parent element, then setting position:relative and left:50%, the child element sets position :relative and left:50% to achieve horizontal centering.

<body>
<div class="container">
    <ul>
        <li><a href=""#>First</a></li>
        <li><a href=""#>Second</a></li>
        <li><a href=""#>Third</a></li>
        <li><a href=""#>Fourth</a></li>
    </ul>
</div>
</body>
 
<style>
.container{
    float:left;
    position:relative;
    left:50%;
}
 
.container ul{
    list-style:none;
    margin:0;
    padding:0;
 
    position:relative;
    left:-50%
}
 
.container li{
    float:left;
    display:inline;
    margin-right:8px
}
</style>

Vertical centering

Vertical centering is divided into two situations: single-line text with a determined height of the parent element and multi-line text with a determined height of the parent element.

A single line of text whose height is determined by the parent element

The method for vertically centering a single line of text whose height is determined by the parent element is to set the height of the parent element to be consistent with line-height. to achieve. height is the height of the element, line-height is the line height, that is, line spacing, which is the distance between the baselines between lines. The calculated difference between line-height and font-size is divided in half (called "line spacing" in CSS) and added to the top and bottom of a line of text. The smallest box that can contain this content is a line box. This kind of text line height and block height brings a disadvantage, that is, when the length of the text content is greater than the width of the block, some content will break away from the block.

<div class="container">
    hello,world!
</div>
 
<style>
.container{
    height:10px;
    line-height:10px;
}
</style>

Multi-line text with a certain height of the parent element

There are two ways to vertically center multi-line text, pictures, etc. with a certain height of the parent element. The first is Insert the table tag and set vertical-align:middle. There is an attribute vertical-align in CSS for vertical centering. When the parent element sets this style, it will be useful for all inline-block type child elements.

/* 方式一 */
<body>
<table><tbody><tr><td class="wrap">
<div>
    <p>居中一下</p>
</div>
</td></tr></tbody></table>
</body>
 
<style>
table td{
    height:500px;
    background:#ccc;
}
</style>
 
/* 方式二 */
<div class="container">
    <div>
        <p>居中一下下</p>
        <p>居中一下下</p>
        <p>居中一下下</p>
        <p>居中一下下</p>
        <p>居中一下下</p>
    </div>
</div>
<style>
.container{
    height:300px;
    background:#ccc;
    display:table-cell;/*IE8以上及Chrome、Firefox*/
    vertical-align:middle;/*IE8以上及Chrome、Firefox*/
}
</style>

In browsers such as chrome, firefox and IE8 or above, you can set the display of block-level elements to table-cell and activate the vertical-align attribute, but note that IE6 and 7 do not support this style.

Invisibly changing the display type

When we set the position:absolute or float:left attribute for an element during our development process, the display type of the element will automatically change to display:inline_block (block-level element), you can set the width and height of the element.

<div class="container">
    <a href="#" title="">点这里看看</a>
</div>
<style>
.container a{
    position;absolute;
    width:200px;
    background:#ccc;
}
</style>

Related recommendations:

The difference between css html element centering and html element content centering

html elements are horizontal and vertical How to set the centering

The above is the detailed content of Introduction to the method of setting the center in html (code). For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
HTML: The Structure, CSS: The Style, JavaScript: The BehaviorHTML: The Structure, CSS: The Style, JavaScript: The BehaviorApr 18, 2025 am 12:09 AM

The roles of HTML, CSS and JavaScript in web development are: 1. HTML defines the web page structure, 2. CSS controls the web page style, and 3. JavaScript adds dynamic behavior. Together, they build the framework, aesthetics and interactivity of modern websites.

The Future of HTML: Evolution and Trends in Web DesignThe Future of HTML: Evolution and Trends in Web DesignApr 17, 2025 am 12:12 AM

The future of HTML is full of infinite possibilities. 1) New features and standards will include more semantic tags and the popularity of WebComponents. 2) The web design trend will continue to develop towards responsive and accessible design. 3) Performance optimization will improve the user experience through responsive image loading and lazy loading technologies.

HTML vs. CSS vs. JavaScript: A Comparative OverviewHTML vs. CSS vs. JavaScript: A Comparative OverviewApr 16, 2025 am 12:04 AM

The roles of HTML, CSS and JavaScript in web development are: HTML is responsible for content structure, CSS is responsible for style, and JavaScript is responsible for dynamic behavior. 1. HTML defines the web page structure and content through tags to ensure semantics. 2. CSS controls the web page style through selectors and attributes to make it beautiful and easy to read. 3. JavaScript controls web page behavior through scripts to achieve dynamic and interactive functions.

HTML: Is It a Programming Language or Something Else?HTML: Is It a Programming Language or Something Else?Apr 15, 2025 am 12:13 AM

HTMLisnotaprogramminglanguage;itisamarkuplanguage.1)HTMLstructuresandformatswebcontentusingtags.2)ItworkswithCSSforstylingandJavaScriptforinteractivity,enhancingwebdevelopment.

HTML: Building the Structure of Web PagesHTML: Building the Structure of Web PagesApr 14, 2025 am 12:14 AM

HTML is the cornerstone of building web page structure. 1. HTML defines the content structure and semantics, and uses, etc. tags. 2. Provide semantic markers, such as, etc., to improve SEO effect. 3. To realize user interaction through tags, pay attention to form verification. 4. Use advanced elements such as, combined with JavaScript to achieve dynamic effects. 5. Common errors include unclosed labels and unquoted attribute values, and verification tools are required. 6. Optimization strategies include reducing HTTP requests, compressing HTML, using semantic tags, etc.

From Text to Websites: The Power of HTMLFrom Text to Websites: The Power of HTMLApr 13, 2025 am 12:07 AM

HTML is a language used to build web pages, defining web page structure and content through tags and attributes. 1) HTML organizes document structure through tags, such as,. 2) The browser parses HTML to build the DOM and renders the web page. 3) New features of HTML5, such as, enhance multimedia functions. 4) Common errors include unclosed labels and unquoted attribute values. 5) Optimization suggestions include using semantic tags and reducing file size.

Understanding HTML, CSS, and JavaScript: A Beginner's GuideUnderstanding HTML, CSS, and JavaScript: A Beginner's GuideApr 12, 2025 am 12:02 AM

WebdevelopmentreliesonHTML,CSS,andJavaScript:1)HTMLstructurescontent,2)CSSstylesit,and3)JavaScriptaddsinteractivity,formingthebasisofmodernwebexperiences.

The Role of HTML: Structuring Web ContentThe Role of HTML: Structuring Web ContentApr 11, 2025 am 12:12 AM

The role of HTML is to define the structure and content of a web page through tags and attributes. 1. HTML organizes content through tags such as , making it easy to read and understand. 2. Use semantic tags such as, etc. to enhance accessibility and SEO. 3. Optimizing HTML code can improve web page loading speed and user experience.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor