有没有办法让div的宽度和里面图片的宽度一样,而忽略父元素的宽度?我的包装器是 1200 像素,我的图像容器的宽度没有设置,容器内的图像没有硬编码,所以我不能硬编码图像容器的宽度。我想让图像容器环绕图像并具有与其相同的宽度。有什么办法吗?
<?php
include 'header.php';
include 'includes/comments.inc.php';
include 'includes/images.inc.php';
?>
<div class="wrapper">
<?php
$imagePath = $_SERVER['QUERY_STRING'];
$realImagePath = substr($imagePath, 1);
$sql = "SELECT * FROM image WHERE path='$realImagePath'";
$result = mysqli_query($conn, $sql);
$getResult = mysqli_fetch_assoc($result);
echo "<div class='imageContainer'>"
."<h1>".$getResult['name'].'</h1>'
.'<div class="relativeContainer"><img class="uploadedRealImg" src="uploads/'.$realImagePath .'" alt="Random image" /></div>'."<br><br>"
.$getResult['description']."<br><br>"
.$getResult['date']."<br><br>"
.$getResult['author']."<br><br></div>";
if (isset($_SESSION['id'])) {
$id = $_SESSION['id'];
$sql2 = "SELECT * FROM user WHERE id='$id'";
$result2 = mysqli_query($conn, $sql2);
$getResult2 = mysqli_fetch_assoc($result2);
if ($getResult2['username'] == $getResult['author']) {
echo "<form method='POST' action='".deleteImage($conn)."'>
<input type='hidden' name='id' value='".$getResult['id']."'>
<input type='hidden' name='path' value='".$getResult['path']."'>
<input type='hidden' name='author' value='".$getResult['author']."'>
<button id='delImage' type='submit' name='imageDelete'>Delete Image</button>
</form>";
}
}
echo "<form method='POST' action='".setComments($conn)."'>
<textarea class='commentSection' name='message'></textarea><br>
<button type='submit' name='commentSubmit'>Comment</button>
</form>";
?>
<div id="comments">
<?php
getComments($conn);
?>
</div>
<?php
echo "<button id='moreComments'>Show more comments</button>";
?>
</div>
<?php
include 'footer.php';
?>
css
.wrapper {
width: 63.1%;
margin: 0 auto;
height: 100%;
}
.imageContainer {
text-align: center;
position: relative;
}
.uploadedImg {
width: 500px;
height: auto;
}
.uploadedRealImg {
max-width: 1200px;
}
.commentSection {
width: 100%;
height: 150px;
}
#delImage {
padding: 0;
border: none;
width: 100px;
height: 100px;
position: absolute;
top: 0px;
right: 0px;
}
.relativeContainer {
position: relative;
}
最佳答案
.imageContainer
是一个div
,一个div
是一个block element . block 元素尝试填充其父级宽度的 100%。
您可以将 .imageContainer
更改为适合其内容的 inline-block
。
.wrapper {
background: purple;
}
.imageContainer {
display: inline-block;
border: 2px solid gold;
}
.image {
display: block; /** optional - if you need the imageContainer height to be the same as that of the image
}
<div class="wrapper">
<div class="imageContainer">
<img class="image" src="https://a.wattpad.com/useravatar/ReaderOfTheReads.256.435663.jpg">
</div>
</div>
关于html - 一个 div 继承了它的父宽度,这不是我想要的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44989671/