How to set a div to be horizontally centered with CSS

醉折花枝作酒筹
Release: 2021-04-09 11:44:25
Original
35817 people have browsed it

How to set the horizontal centering of divs with CSS: 1. Set the "margin: 0 auto" style to the div element; 2. Set the "text-align: center" style in the parent div element, at the child level Set the "display: inline-block" style in the div element.

How to set a div to be horizontally centered with CSS

The operating environment of this tutorial: Windows7 system, CSS3&&HTML5 version, Dell G3 computer.

1. Adaptive margins

Method:Element binding attributes:margin: 0 auto;

Copy after login

Effect:

Note:Commonly used, suitable for known parent element width Situation

2. Inline block element

Method:Parent element setting attribute:text-align: center;

     Set attributes for sub-level elements:display: inline-block;

Copy after login

The effect is as shown:

Note:Inline-block has browser compatibility issues, and the side effects caused by setting inline-block will be dealt with separately.

Supplement: Use positioning

Method:Parent element setting attribute:position: relative;

##1 -level element setting attributes:posity: absolute;

Copy after login

effect As shown

#Note:

Applicable to situations where the width of the parent element is known. It is troublesome to set the center positioning yourself.

【Recommended learning:

css video tutorial

The above is the detailed content of How to set a div to be horizontally centered with CSS. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!