简体   繁体   English

CSS元素宽度问题

[英]Problem with CSS Element width

When I create a div, its width is nearly 90% of the screen, but I want it to be minimal size it should be. 创建div时,其宽度接近屏幕的90%,但我希望它的尺寸​​应尽可能小。 How can I fix it with CSS? 如何使用CSS修复? Any ideas? 有任何想法吗?

If you float the div to the left or right, and display it as a block, then it will only be the width it needs to be. 如果将div向左或向右浮动,并将其显示为一个块,那么它将仅是所需的宽度。

float: left;
display: block;

Then you can also give it a width. 然后,您也可以给它一个宽度。 The reason yours is "nearly 90%" is because by default, there will be padding/margins on the elements. 您之所以“接近90%”是因为默认情况下,元素上会有填充/边距。

Can we see your code? 我们可以看到您的代码吗? If you want to remove the block-qualities of a div all you have to do is add display:inline-block to that div and it should just take up the space it carries. 如果要删除div的块质量,您要做的就是在该div上添加display:inline-block ,它应该只占用其携带的空间。

您可以在<div>上使用display: inline-block ,但是IE7和更早版本不支持该功能,但本机内联对象除外。

The width of any element will depend on the width of its parent element (except pixels) . 任何元素的宽度将取决于其父元素(像素除外)的宽度。 It might have been that you set width on each of its parent elements that you ended up being confused on the child element's box model. 可能是因为您在其每个父元素上设置了宽度,最终使您对子元素的框模型感到困惑。 If no width is specified on the child element, then it will inherit the width of its parent element. 如果未在子元素上指定宽度,则它将继承其父元素的宽度。

For example: 例如:

Markup Code: 标记代码:

<html>
    <body>
        <div class="outer">
            <div class="inner"></div>
        </div>
    </body>
</html>

CSS Code: CSS代码:

body {
    width: 960px;
}
.outer {
    width: 75%;
}
.inner {
    width: 50%;
}

Details: 细节:

In the above example, you might think that <div class="inner"> 's width (which is 50%) will adjust according to the <body> 's width (which is 960px) . 在上面的示例中,您可能认为<div class="inner">的宽度(50%)将根据<body>的宽度(960px)进行调整

However, that will not happen, because we already adjusted its parent element: <div class="outer"> (which is 75%) . 但是,这不会发生,因为我们已经调整了其父元素: <div class="outer"> (75%) So what really happened is that <div class="inner"> is adjusting its width according to <div class="outer"> 's width not <body>'s . 所以真正发生的是<div class="inner">的宽度是根据<div class="outer">的宽度而不是<body>'s的宽度<body>'s

<div class="inner"> 's final width computation: <div class="inner">的最终宽度计算:

  • <body> (960px) * <div class="outer"> * (0.75) = <div class="outer"> 's final width ( 720px ) <body> (960px) * <div class="outer"> * (0.75) = <div class="outer">的最终宽度720px
  • <div class="outer"> (720px) * <div class="inner"> (0.50) = <div class="inner"> 's final width ( 360px ) <div class="outer"> (720px) * <div class="inner"> (0.50) = <div class="inner">的最终宽度360px

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

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