父级和子级div之间的CSS高度和宽度不一致

问题描述 投票:2回答:1

我试图创建一个标题,左侧显示标题,右侧显示按钮列表。要实现这一点,需要一个父#ChatHeader div,它包含两个子div,#ChatHeaderTitle和#ChatHeaderControls。

由于某种原因,父div中8vh的高度与子div中8vh的高度相同。两个div的高度都设置为8vh,但父div显得小于孩子。我也有宽度相同的问题。

我确定我错过了一些明显的东西,但我一直在尝试我能想到的一切,并且无法解决它。

我的HTML的简化版本:

<div id='ChatHeader'>
    <div id='ChatHeaderTitle'>
        Title
    </div>
    <div id='ChatHeaderControls'>
        Controls
    </div>
</div>

听到我的CSS:

#ChatHeader {
    width:100%;
    height: 8vh;
    overflow: hidden;

    background-color: #000000;
    color: var(--std-background-colour);   
}

#ChatHeaderTitle {
    height: 8vh;
    width: calc(100% - 8vh);

    padding:1vh;
}

#ChatHeaderControls {
    height: 8vh;
    width: 8vh;

    float:right;
    padding: 1vh;
    font-size:1.5vh;
    color: var(--std-background-colour);
}
html css web height width
1个回答
1
投票

在填充和边距上进行重置总是一个好主意,所以你知道你是从一个干净的石板开始的。

基本的 - 你在右侧div上有填充,它将div扩展到比你想要的更大。是的,填充在div的内部是可见的,但它会将填充量扩展div。如果你想使用1.5vh的填充,你应该使你的右边8vh + 1.5vh = 9.5vh(或8vh - 1.5vh = 6.5vh,取决于你的盒子里有什么),而不是8vh。 "By default in the CSS box model, the width and height you assign to an element is applied only to the element's content box. If the element has any border or padding, this is then added to the width and height to arrive at the size of the box that's rendered on the screen. This means that when you set width and height, you have to adjust the value you give to allow for any border or padding that may be added."

此外,你的第二个div漂浮到右边,但你的第一个div没有漂浮到左边 - 所以你的花车不太正确。如果向左侧div添加左浮动,则遵循右浮点div。

我有下面的代码,对你有用。但是,如果我是你,我会考虑将其转换为网格布局,而不是浮动的div - 它最终会让你的生活更轻松。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <title></title>
    <style type="text/css">
        body, #ChatHeader, #ChatHeaderTitle, #ChatHeaderControls {
            padding : 0px ; 
            margin : 0px ; 
        }
        #ChatHeader {
            width:100%;
            height: 8vh;
            overflow: hidden;
            background-color: #000000;
        }       
        #ChatHeaderTitle {
            height: 8vh;
            width: calc(100% - 8vh);
            background-color : pink ; 
            padding:0vh;
            float : left ; 
        }       
        #ChatHeaderControls {
            height: 8vh;
            width: 8vh;
            background-color : blue ; 
            font-size:1.5vh;
            float : right ; 
        }
    </style>

</head>
<body>
<div id='ChatHeader'>
    <div id='ChatHeaderTitle'>
        Title
    </div>
    <div id='ChatHeaderControls'>
        Controls
    </div>
</div>
</body>
</html>
© www.soinside.com 2019 - 2024. All rights reserved.