让元素居中的几种方法

一、让元素水平居中

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%); 
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 问答题47 /72 常见浏览器兼容性问题与解决方案? 参考答案 (1)浏览器兼容问题一:不同浏览器的标签默认的外补...
    _Yfling阅读 14,687评论 1 92
  • 收听音频,戳链接,旧号itclan已暂停使用,欢迎关注微信itclanCoder公众号可收听更多音频 前言 关于网...
    itclanCoder阅读 12,533评论 3 30
  • 还有几天就是农历新年了,于我们而言这是个举国欢庆、阖家团员的大日子。提前祝各位朋友新年快乐,家人健康。言归正传,借...
    崔小叨阅读 4,158评论 1 11
  • 绝对想不到的是,此时此刻,他正在电话的另一端。做着他应聘公司出的考题数据。 我进屋,妈妈说,是要打电话吗?不是,我...
    KinJ阅读 2,540评论 0 0
  • 最终目标希望完成如下几个功能: (1)登录校园网 (2)登出校园网 (3)查询当前网络状态 (4)查询流量、帐户余...
    胡哈哈哈阅读 4,108评论 0 1