让元素居中的几种方法

作者: 味蕾里的青春 | 来源:发表于2016-08-12 22:48 被阅读80次

一、让元素水平居中

1.想要一个块级元素在其包含元素内居中,可以将此块级元素的左、右外边距的值设为auto。

html代码:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
  <div class="box1">
    <p class="box2">
      This is a paragraph with a fixed width,
      and left and right margins set to auto,
      So it's centered.
    </p>
  </div>
</body>
</html>

CSS代码:

.box1 {
  background-color:pink;
  width:400px;
  height:100px;
}

.box2 {
  background-color:green;
  width:300px;
  height:50px;
  margin-left:auto;
  margin-right:auto;
}

Output:


output1.png

2.想要一个inline元素、或inline-block元素在其包含元素内居中,可以将其被包含元素设置为 text-align:center

html代码:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
  <div class="box1">
    <p class="box2">
      This is a paragraph with a fixed width,
      and left and right margins set to auto,
      So it's centered.<br>
    </p>
    <p class="box3">  <a href="hicc.me">想了解更多请点击。</a>
    </p>
  </div>
</body>
</html>

CSS代码:

.box1 {
  background-color:pink;
  width:500px;
  height:200px;
}

.box2 {
  background-color:green;
  width:450px;
  height:80px;
  margin-left:auto;
  margin-right:auto;
}

.box3 {
  width:400px;
  background-color:blue;
  height:80px;
  text-align:center;
}

a {
  background-color:yellow; 
}

Output:

output2.png

二、让元素垂直居中

在transform: translateY的帮助下我们可以使用三行CSS代码让任何甚至不知道高度的元素垂直居中。CSS的transform属性常用来旋转和缩放元素,现在我们可以使用它的translateY函数垂直对齐元素。
垂直居中通常的做法是使用绝对定位或者设置行高,但是这两种方案的弊端是要么需要你知道元素的高度,要么只能作用于单行文本(注:inline或者inline-block元素)。

代码如下:

.element { 
   position: relative; 
   top: 50%; 
   transform: translateY(-50%); 
}

相关文章

  • 文字与元素居中的方式

    我们经常会让元素进行上下左右的居中,这里提供几种方法供大家使用 我们经常会让元素进行上下左右的居中,这里提供几种方...

  • CSS垂直居中,你会多少种写法?

    CSS控制居中是前端开发中非常常用的布局技能,本文列出几种CSS控制元素居中的几种方法。  谈及HTML元素居中展...

  • CSS居中小结

    下面是CSS居中的几种方法: 水平居中元素: 通用方法,元素的宽高未知 方式一:CSS3 transform 方式...

  • 让元素居中的几种方法

    一、让元素水平居中 1.想要一个块级元素在其包含元素内居中,可以将此块级元素的左、右外边距的值设为auto。 ht...

  • CSS居中方法大全

    水平居中 内联元素text-align: center 这个属性会让内联子元素水平居中 块级元素 水平居中通用方法...

  • 元素居中的几种方法

    flexbox 绝对定位 + transform

  • CSS水平居中和垂直居中的方法

    本篇文章主要介绍本人最近在CSS学习中整理总结出的水平&垂直居中的几种方法 水平居中 子元素为行内元素、单个块状及...

  • css3 元素居中的几个方法

    原文参考 纯CSS实现垂直居中的几种方法 html 当元素为 block时 position position +...

  • 2020-09-07

    子元素如何居中的几种方法 1. 已知盒子大小: 1) 子盒子:定位+margin(position:...

  • 块级元素在块级元素垂直左右居中 和(文字加图片水平居中)

    垂直左右居中的几种方法 方法一:绝对定位(子元素可以未知高度和宽度) 方法二:做单元格处理(父元素需要输入固定高度...

网友评论

    本文标题:让元素居中的几种方法

    本文链接:https://www.haomeiwen.com/subject/qqknjttx.html