简体   繁体   English

不能在 div 元素内水平居中 div 元素

[英]Cannot horizontally center a div element within a div element

I'm developing a layout, and in this layout there are four div elements yellow, green, blue, gray.我正在开发一个布局,在这个布局中有四个 div 元素黄色、绿色、蓝色、灰色。 I want to horizontally center the green div within the yellow div.我想将黄色 div 中的绿色 div 水平居中。

Tried "margin: auto;"试过"margin: auto;" and other css ways, also w3-css ways as well.和其他 css 方式,还有 w3-css 方式。 But I can't seem to center it.但我似乎无法将其居中。 What did I do wrong?我做错什么了?

<!doctype html>

<html>

<head>
    <title>Layout</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
    <style>
    </style>


</head>

<body>
    <div class="" style="width:100vw;height:100vh">

        <div class="" style="height:47px; width:100%; position: absolute;  z-index:2">
            <div class="w3-bar" style="background-color: #2f4f4f; ">
            </div>
        </div>

        <div class="w3-row" style="height:100%; width:100%; position: fixed; ">

            <div class="w3-col w3-animate-left w3-collapse " style="height:100%; width:296px; z-index:1; background-color: yellow; " id="sidebar">
                
                <div
                    style="position: absolute; top: 47px; width:280px; height:500px; margin: auto; background-color: green">
                </div>

            </div>

            <div class="w3-rest " style="height:100%; ">
                <div style="height:97%; background-color: blue;">
                </div>

                <div style="height:3%; width:100%; background-color: gray;">
                <div>

</body>

</html>
position: absolute;
top: 50%;
width: 280px;
height: 500px;
margin: auto;
transform: translateY(-50%);
background-color: green;

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

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