search
HomeWeb Front-endJS TutorialJavaScript implements vertical and horizontal centering in specified elements_javascript skills

本章节介绍一下如何实现未知宽高的元素在指定元素下实现垂直水平居中效果,下面就以span元素为例子,介绍一下如何实现span元素在div中实现水平垂直居中效果,代码如下:

<!DOCTYPE html>
<html>
<head>
<meta charset=" utf-8">
<style type="text/css">
#box{
 width:200px;
 height:150px;
 background:blue;
 position:relative;
}
#antzone{
 background:green;
}
</style>
<script type="text/javascript">
window.onload=function(){
 var obox=document.getElementById("box");
 var oantzone=document.getElementById("antzone");
 var w=oantzone.offsetWidth;
 var h=oantzone.offsetHeight;
 oantzone.style.position="absolute";
 oantzone.style.left="50%";
 oantzone.style.top="50%";
 
 oantzone.style.marginLeft=-(w/2)+"px";
 oantzone.style.marginTop=-(h/2)+"px";
}
</script>
</head>
<body>
<div id="box">
 <spanj id="antzone">脚本之家</span>
</div>
</body>
</html>

上面你的代码实现了span元素在div中垂直水平居中效果,下面简单介绍一下它的实现过程。

一.实现原理:
虽然css为明确给出span元素的尺寸,但是它毕竟有一个尺寸的,这个尺寸可以使用offsetWidth和offsetHeight属性获取,然后将此span元素设置为绝对定位,然后再将left和top属性值分别设置为50%,但是这个时候并不是span元素的中心点垂直水平居中,而是span元素的左上角垂直水平居中,然后在设置span元素的负的外边距,尺寸是span元素宽高的一半,这样就实现了垂直水平居中效果。

例子二:

思路:实现起来最麻烦的其实是水平居中和垂直居中,其中垂直居中是最麻烦的。考虑到浏览器兼容性,网上看了一些资料,发现在页面中垂直居中确实没有什么太好的办法。于是就采用了position:fixed属性控制时钟的绝对位置,通过clientWidth和clientHeight来获取时钟的宽和高,利用javascript控制marginLeft和marginTop来居中时钟。

<!doctype html> 
<html lang="en"> 
<head> 
  <meta charset="UTF-8"> 
  <title>Centered Clock</title> 
  <style type="text/css"> 
 
    body{ 
      background: #fff; 
    } 
 
    body, div, p{ 
      margin: 0; 
      padding: 0; 
    } 
     
    .center{ 
      position: fixed; 
      left: 50%; 
      top: 50%; 
    } 
 
    .box{ 
      border: 1px solid #000; 
      padding: 20px 30px; 
      font-size: 1.5em; 
      font-weight: 500; 
      margin: auto auto; 
    } 
 
  </style> 
</head> 
<body> 
  <div class="center"> 
    <p class="box"></p> 
  </div> 
</body> 
<script type="text/javascript"> 
  window.onload = function () { 
     
    getTimes(); 
    var box = document.getElementsByClassName("box")[0]; 
    box.style.marginLeft = -box.clientWidth / 2 + "px"; 
    box.style.marginTop = -box.clientHeight / 2 + "px"; 
    setInterval(getTimes, 1000); 
  } 
 
  function getTimes() { 
 
    var box = document.getElementsByClassName("box")[0]; 
 
    var dateTime = new Date(); 
    var year = dateTime.getFullYear(); 
    var date = dateTime.getDate(); 
    var month = dateTime.getMonth() + 1; 
    var hours = dateTime.getHours(); 
    var minutes = dateTime.getMinutes(); 
    var secondes = dateTime.getSeconds(); 
 
    box.innerHTML = year + "-" + format(month) + "-" + format(date) + " " + format(hours) + ":"+ format(minutes) +":" + format(secondes); 
  } 
 
  function format(a) { 
    return a.toString().replace(/^(\d)$/, "0$1"); 
  } 
 
</script> 
</html>

例子三:

思路:采用相对定位,设定left和top值为(pw-w)/2和(ph-h)/w,其中pw和ph为外部标签的宽与高,w和h为内部标签的宽与高。

核心代码:


以上就是给大家总结的三种javascript实现居中的例子,小伙伴们可以参考下,希望对大家能够有所帮助。

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
Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

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.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools