【问题标题】:How to set center elements in body without centering all elements within main elements?如何在主体中设置中心元素而不将主要元素中的所有元素居中?
【发布时间】:2020-01-29 07:54:58
【问题描述】:

我正在尝试将 text-align: center 设置为 body 以使我的 div 在其中正常工作,但这会在我的页面中将所有文本居中。如何将 text-align 设置为正文,使其仅影响正文和其中的 div,而不影响 div 中的所有内容?

HTML:

<body>
<div class="leftColumn"><!--stuff--></div>
<div class="centerColumn"><!--stuff--></div>
<div class="rightColumn"><!--stuff--></div>
</body>

CSS:

.leftColumn, .centerColumn, .rightColumn {
    margin: 16px;
    border: 2px solid var(--medium) !important;
    background-color: white !important;
    margin-top: 98px !important;
    display: inline-block;
}

.leftColumn, rightColumn {
    width: 300px;
}

.centerColumn{
    min-width: 900px;
    margin: auto; /* This doesn't center the center column so I'm trying to use text-align to center this. */
}

.rightColumn {
    float: right;
    right: 16px;
}

【问题讨论】:

  • 元素从其父元素继承属性。在这种情况下,您必须重置列上的 text-align 属性,否则因为它们将继承父级上设置的 text-align:center 属性

标签: html css center text-align


【解决方案1】:

你的代码:

.leftColumn, .centerColumn, .rightColumn {
    margin: 16px;
    border: 2px solid var(--medium) !important;
    background-color: white !important;
    margin-top: 98px !important;
    display: inline-block;
}

解决方案:

.leftColumn, .centerColumn, .rightColumn {
    margin: 16px;
    border: 2px solid var(--medium) !important;
    background-color: white !important;
    margin-top: 98px !important;
    display: inline-block;
    text-align: left; /* setting alignment inside */
}

加:

body{
   text-align: center; /*  setting alignment outside */
}

如果它不起作用,请发表评论:)

【讨论】:

    【解决方案2】:
    body{
       text-align: center;
    }
    

    这将使主体在 css 代码中居中。此外,对于您想要居中的特定事物,给它一个 id &lt;div id = "demo"&gt;&lt;/div&gt; 并将 css 中的 body 替换为 id。

    【讨论】:

      猜你喜欢
      • 2011-02-03
      • 1970-01-01
      • 2022-08-21
      • 1970-01-01
      • 2010-12-29
      • 2010-11-15
      • 1970-01-01
      • 2021-03-04
      • 2022-01-04
      相关资源
      最近更新 更多