How to center HTML elements through absolute positioning and fixed positioning of css?

不言
Release: 2018-11-06 09:55:10
Original
2926 people have browsed it

Many people try to center elements such as modal boxes in the center of the page through CSS, but they fail, and then they use JS to complete it. In this technical article, I will show you how to center an element without using JavaScript. Without further ado, let’s get straight into the text.

The method is relatively simple, that is, not just using one wrapping element, but using two elements. (Recommended course: css video tutorial)

HTML:

<div class="popup">
  <div class="wrapper">
       some content
    </div>
</div>
Copy after login

CSS:

.popup{
   position:fixed;
 left:50%;  
}
Copy after login

This CSS centers the left side of the element to the center of the window, But we want the modal box to be centered based on the middle position of the element.

Now let's look at the trick approach, since we have two wrappers for the popup we can manipulate the inner div and tell the div to move left -50% relative and because it Inside the container, the div will only move half its size to the left. That's how we bring the modal together.

Add CSS

.popup .wrapper{
  position:relative; 
  left:-50%;
}
Copy after login

Then our element is placed in the horizontal center, thus achieving the centering of the element.

This article ends here. For more exciting content, you can pay attention to the Video Tutorial column of the PHP Chinese website! ! !

The above is the detailed content of How to center HTML elements through absolute positioning and fixed positioning of 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template