Simple center a object with css and no hacks

2020-05-18 11:49发布

I want to center an object using CSS and no hacks, is this possible and how?

I have tried this, but than my p tag is gone.

.centered {
  position: fixed;
  top: 50%;
  left: 50%;
}

标签: html css center
7条回答
▲ chillily
2楼-- · 2020-05-18 11:52

Use this for general purposes. Even span or div which is inside whatever :

width:inherit; display:block;margin:0 auto;
查看更多
smile是对你的礼貌
3楼-- · 2020-05-18 11:58

late into the game, but have you tried with display:flex on the parent ?

I have a useful class that is simple and works with all type of elements:

/* apply this on the parent */
.center {
    display:flex;
    align-items: center; /*vertical alignement*/
    justify-content: center; /* horizontal alignement*/
}

This is relatively new but supported at ~98% of major browsers.

However I suggest that you learn a bit about flexBox, it may seem complicated at first but it is very powerful for all type layouts !

查看更多
Evening l夕情丶
4楼-- · 2020-05-18 12:07

HTML:

<div>Centered</div>

CSS:

div {
    margin: 0 auto;
    width: 200px;
}

Live example: http://jsfiddle.net/v3WL5/

Note that margin: 0 auto; will only have an effect if the div has a width.

查看更多
Emotional °昔
5楼-- · 2020-05-18 12:12

Use margin: auto like this:

margin: 0px auto
查看更多
Root(大扎)
6楼-- · 2020-05-18 12:14

Usage :

  1. In-Line usage : Content goes here....
  2. CSS Code :

    #text-align { text-align:center }

HTML Code :

<div id="text-align">Content goes here....</div>

http://www.techulator.com/resources/4299-center-Deprecated-tags-HTML.aspx

查看更多
放我归山
7楼-- · 2020-05-18 12:14

if you don't need to be position:fixed; you can just use

<center>
Hello
</center>

This is deprecated in HTML5

查看更多
登录 后发表回答