如何在主体中设置居中元素而不将主要元素中的所有元素居中?

How to set center elements in body without centering all elements within main elements?

我正在尝试将 text-align: center 设置为 body 以使我的 div 正常工作,但这样会使我页面中所有文本居中。如何将文本对齐设置为正文,以便它只影响正文和其中的 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;
}

您的代码:

.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 */
}

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

body{
   text-align: center;
}

这将使正文在 css 代码中居中。此外,对于您想要居中的特定内容,为其指定一个 ID <div id = "demo"></div> 并将 css 中的正文替换为该 ID。