且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

CSS宽度/高度具有与HTML宽度/高度属性不同的效果,具体取决于元素类型

更新时间:2023-02-13 16:39:27

code> div 元素没有 height width 属性。如果在标记中指定这些属性,它们将被完全忽略。你只能通过CSS样式来定义一个div。



img 另一方面,元素有这些属性。



请参阅 div img 相关。


For example, they cause completely different behavior in regards to auto margins.

Check out this fiddle: https://jsfiddle.net/L1rk46xy/

<style>
.fixed {
    display:fixed;
    top:0px;
    left:0px;
    right:0px;
    bottom:0px;
}
.centered {
    position:absolute;
    margin:auto;
    top:0;
    left:0;
    right:0;
    bottom:0;
}
</style>
<div class="fixed">
    <div class="centered" style="width:100px;height:30px;" width="200" height="30">
        CENTERED
    </div>
</div>

It has a fixed element to fill the viewport, and inside that there's some centered text. In my actual web app, this is a loading indicator that's supposed to be centered above content. In order for margin:auto to work, the centered element needs to have top/right/bottom/left all set to zero and it needs to have a width and height. (Note: I'm explicitly avoiding the alternative centering method of using a top/left:50%, because it requires a hard-coded negative half-offset of the size, whereas this method will work for any size object).

Notice in the fiddle how the div element with text is centered. Now, remove the style attribute that sets the width/height and leave only the HTML width/height attributes on the centered div. The div element is no longer centered.

Furthermore, if you replace the div with an img, then HTML width/height attribute ARE sufficient to center it. What is going on here? Why the difference in CSS vs HTML attributes and between DIV and IMG tags? This occurs regardless of whether these elements are block or inline (e.g. it uses absolute positioning anyway).

The answer is that div elements don't have height and width attributes. If you specify those attributes in the markup, they are completely ignored. You can only size a div through CSS styles.

img elements on the other hand, do have those attributes.

See div vs img.