Html css“左”不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14171855/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 04:44:54  来源:igfitidea点击:

css "left" not working

htmlcsspositioning

提问by Oto Shavadze

I have 2 divs, parent and child, I want that child left side (left border) will in center of parent.

我有 2 个 div,父母和孩子,我希望孩子的左侧(左边框)位于父母的中心。

Why this code not working? that is left: 50%for child, is not working.

为什么这段代码不起作用?那是left: 50%给孩子的,不起作用。

<div id="outher">
    <div id="inner">

    </div>
</div>

css:

css:

#outher {
   width: 1000px;
   height: 1000px;
   background-color: #ccc;
}

#inner {
   width: 400px;
   height: 300px;
   background-color: #090;
   left: 50%;
}

demo http://jsfiddle.net/vrse2/5/

演示http://jsfiddle.net/vrse2/5/

回答by Paul Fleming

You need to set positionto absoluteor relative:

您需要设置positionabsoluterelative

#inner {
   width: 400px;
   height: 300px;
   background-color: #090;
   position: absolute;
   left: 50%;
}

回答by NullPoiиteя

CSS leftonly works with positioned elements.

CSSleft仅适用于定位元素。

Quoted from W3C

引用自 W3C

Values  <length> | <percentage> | auto | inherit
Initial value   auto
Applies to  positioned elements
Inherited   No

Try

尝试

#inner {
   width: 400px;
   height: 300px;
   background-color: #090;
   position: absolute;
   left: 50%;
}


Good read

好读

  1. MDN : CSS Reference -left (Best IMHO)
  2. W3C : CSS/Properties/left
  1. MDN:CSS 参考 -left(最好的恕我直言)
  2. W3C : CSS/属性/左

回答by Mateusz Rogulski

You need to add position: absolute;to your CSS. leftis used for absolute positioning.

您需要添加position: absolute;到您的 CSS。left用于绝对定位。

In your case:

在你的情况下:

#inner {
   width: 400px;
   height: 300px;
   background-color: #090;
   position: absolute;
   left: 50%;
}

回答by Tom Walters

Use:

用:

margin-left: 50%;

Or:

或者:

position:relative;
left:50%;

回答by John Peter

Try With the following :

尝试使用以下方法:

HTML Part :

HTML 部分:

<div id="outher">
    <div id="inner">

    </div>
</div>

CSS Part :

CSS 部分:

#outher {
    width: 1000px;
    height: 1000px;
    background-color: #ccc;
}

#inner {
    width: 400px;
    height: 300px;
    background-color: #090;
    left: 50%;  
    margin:0 auto;
    position: absolute;
}

I think this may help you to resolve your problem.

我认为这可以帮助您解决问题。