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条回答
The star\"
2楼-- · 2020-05-18 12:15

There's several ways to center an element. But it depends on what your element is and how we choose to display it:

  • If you have {display:inline; }

    This is simple. You can just use "text-align: center;" to center text, images and divs.

  • If you have {display:block;}

    This is a bit more difficult. It depends on how your object is positioned. Your object could be relative, absolute, or fixed.

    • If it is relative; then you can use "margin:0 auto;", however you will require a width value.

    • If it is absolutely positioned, then you need to specify your "top:" and "left:" values. You'll also need a width. If you know the width of the element, the best way is to use {left:50%; margin-left:-X}, where X = 1/2 the width of the element.

查看更多
登录 后发表回答