简体   繁体   中英

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. 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. However, if the text inside this element does not exceed this max-width, the element is positioned with a 15% margin on the left.

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%; is reached.

To actually center an element (as opposed to centering the text within it) you can use CSS flex on its container.

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.

 .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; to center the element or you can use <center></center> tag in HTML to center the element

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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