如何在不影响中心对齐的情况下将填充应用于div?

时间:2014-10-01 01:46:12

标签: html css

非常简单的测试用例:

<!DOCTYPE html>
<html>
    <head>
        <title>Weird Centering Demo</title>
        <style type='text/css'>
            body
            {
                margin: 0px;
            }

            .test1
            {
                width: 100%;
                padding: 100px;
                text-align: center;
                background-color: #acf;
            }

            .test2
            {
                width: 100%;
                padding: 10px;
                text-align: center;
                background-color: #aaf;
            }
        </style>
    </head>
    <body>
        <div class='test1'>Test 1</div>
        <div class='test2'>Test 2</div>
    </body>
</html>

上面页面中的两个div应该以它们包含的文本为中心。但是,以某种方式增加测试1的填充将其文本移动到右侧。在chrome开发人员工具中检查时,看起来100px填充适用于左侧而非右侧。我无法理解这种不对称的行为,也没有运气试验单独设置padding-left和padding-right。

在不改变居中文本对齐的情况下应用填充的惯用方法是什么?

2 个答案:

答案 0 :(得分:3)

向左和/或向右添加填充会增加包含div的块框的宽度。

如果将宽度设置为100%,则计算出的宽度将比页面和原因宽 和溢出情况。

如果内容溢出,则它不会居中,而是左对齐。

您可以通过添加属性box-sizing: border-box来解决问题 它将包含块块边缘内的填充。

但是,最佳解决方案取决于您的设计细节。

您可以在http://www.w3.org/TR/css3-ui/#box-sizing

了解有关盒子大小调整的更多信息

body {
  margin: 0px;
}
.test1 {
  width: 100%;
  padding: 100px;
  text-align: center;
  background-color: #acf;
  box-sizing: border-box;
}
.test2 {
  width: 100%;
  padding: 10px;
  text-align: center;
  background-color: #aaf;
  box-sizing: border-box;
}
<div class='test1'>Test 1</div>
<div class='test2'>Test 2</div>

答案 1 :(得分:-1)

你有一个添加10px,但另一个是添加100px。

由于宽度均为100%且填充不同,因此一个文本与另一个文本偏离中心,因为一个文件的宽度比另一个宽。[/ p>

通过同时使用相同的宽度(主要)和/或相同的填充(辅助)来修复它。

http://www.codeacademy.com上进行互动且有趣的学习课程:快速链接到css框模型(如果链接适合您):http://www.codecademy.com/courses/web-beginner-en-6merh/0/1?curriculum_id=50579fb998b470000202dc8b