简体   繁体   English

如何使用 css 在页面上居中 HTML 元素

[英]How can i center an HTML element on the page using css

I am trying to position an HTML element in the center of a page.我正在尝试在页面中心 position 一个 HTML 元素。 I want to make the center of the element in the center of the page.我想使元素的中心位于页面的中心。

Currently, my code looks like this目前,我的代码看起来像这样

#associate {
    position:absolute;
    color:white;
    background-color:red;
    margin-top:55px;
    margin-left:15%;
    margin-right:15%;
    max-width:70%;
    text-align:center;
    padding:2.5%;
    max-height:17.5%;
    border-radius:25px;
    border-style:outset;
    border-color:white;
    border-width:5px;
}

If the text in this element is long enough (enough to exceed the max-width:70%; ), the element is centered on the page exactly how i want it to be.如果此元素中的文本足够长(足以超过max-width:70%; ),则该元素将完全以我想要的方式居中在页面上。 However, if the text inside this element does not exceed this max-width, the element is positioned with a 15% margin on the left.但是,如果此元素内的文本不超过此最大宽度,则该元素将在左侧以 15% 的边距定位。

A little while ago, when I was trying to rotate an element, I was able to choose the rotation point of the element with不久前,当我试图旋转一个元素时,我可以选择元素的旋转点

transform-origin:0% 50%;
transform:rotate(90deg);

is there a similar way to choose the point in the element where it will center on the page?有没有类似的方法来选择元素中的点,它将在页面上居中? I would like to position the center of the element in the center of the page and have the ends of the element expand when needed to fit more text until the max-width:70%;我想 position 将元素的中心放在页面的中心,并在需要时扩展元素的末端以适应更多文本,直到max-width:70%; is reached.到达了。

To actually center an element (as opposed to centering the text within it) you can use CSS flex on its container.要实际居中一个元素(而不是居中其中的文本),您可以在其容器上使用 CSS flex。

This snippet puts your element in a container which has the viewport dimensions and uses the justify-content and align-items CSS properties to center it horizntally and vertically.此代码段将您的元素放在具有视口尺寸的容器中,并使用 justify-content 和 align-items CSS 属性将其水平和垂直居中。

 .container { display: flex; justify-content: center; align-items: center; height: 100vh; width: 100vw; } #associate { position: absolute; color: white; background-color: red; margin-top: 55px; margin-left: 15%; margin-right: 15%; max-width: 70%; text-align: center; padding: 2.5%; max-height: 17.5%; border-radius: 25px; border-style: outset; border-color: white; border-width: 5px; }
 <div class="container"> <div id="associate"> Here is some content<br> And another line of it. </div> </div>

you can use text-align:center;你可以使用text-align:center; to center the element or you can use <center></center> tag in HTML to center the element使元素居中,或者您可以使用 HTML 中的<center></center>标签使元素居中

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM