The pure js Code enables the vertical and horizontal center display of elements with unknown width and height in the specified element, and the js Element

Source: Internet
Author: User

The pure js Code enables the vertical and horizontal center display of elements with unknown width and height in the specified element, and the js Element

The following uses the span element as an example to describe howImplement the horizontal vertical center effect of the span element in the divThe Code is as follows:

<! DOCTYPE html> 

The above code implements the vertical and horizontal center effect of the span element in the div. The following describes the implementation process of the span element.

I. Implementation principle:

Although css clearly defines the size of the span element, it has a size after all. this size can be obtained using the offsetWidth and offsetHeight attributes, and then the span element is set to absolute positioning, then, set the left and top attribute values to 50% respectively, but this is not the center point vertical and horizontal center of the span element, but the vertical and horizontal center of the upper left corner of the span element, then, when the negative margin of the span element is set, the size is half the width and height of the span element. This achieves the vertical and horizontal center effect.

The above is all the content of this article. We will update the Usage Details of attributes such as scrollTop, offsetHeight, and offsetTop in the future. Please stay tuned to this site. Thank you.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.