100% width extends past parent element

I'm using HTML and CSS to code a card-like button.

For some reason, the width of the text under the image always extends past the edge of the parent div .

I can adjust to make it relatively unnoticeable when viewing on desktop, but it becomes a real pain when it comes to viewing on mobile devices.

.card {
  width: 20%;
  box-shadow: 0px 0px 10px gray;
}
.card:hover {
  box-shadow: 0px 0px 20px black;
}
.card-img {
  width: 100%;
}
.card-title {
  margin: 10px;
  display: inline-block;
  font-family: Open Sans;
  text-align: center;
  width: 100%;
}
<div class="card">
  <img class="card-img" src="http://prww-weather.com/logo.png" />
  <p class="card-title">Card Title</p>
</div>

You can try this:

https://jsfiddle.net/nbLLgx5x/

.card {
    width: 20%;
    box-shadow: 0px 0px 10px gray;
}

.card:hover {
    box-shadow: 0px 0px 20px black;
}

.card-img {
    width: 100%;
    display: block;
}

.card-title {
    padding: 10px;
    font-family: Open Sans;
    text-align: center;
    margin: 0;
}
<div class="card">
    <img class="card-img" src="http://prww-weather.com/logo.png" />
    <p class="card-title">This is a very long card title</p>
</div>

使用paddingborder-box

 .card {
  width: 20%;
  box-shadow: 0px 0px 10px gray;
}
.card:hover {
  box-shadow: 0px 0px 20px black;
}
.card-img {
  width: 100%;
}
.card-title {
margin: 0;
  padding: 10px 0;
  display: inline-block;
  font-family: Open Sans;
  text-align: center;
  width: 100%;
  box-sizing: border-box;
}
<div class="card">
  <img class="card-img" src="http://prww-weather.com/logo.png" />
  <p class="card-title">Card Title</p>
</div>

It is all due to margin:10px that you have assigned for card-title. That will consume 100% of the parent width + 10px on left and 10px on the right

To have a gutter space around the card-title and constrain it within parent bounds, use padding:10px for card-title, and enable box-sizing: border-box; property on all elements. (border-box will allow the padding, borders to be considered as part of element width itself)

* {
   box-sizing: border-box;
}
.card {
  width: 20%;
  box-shadow: 0px 0px 10px gray;
}
.card:hover {
  box-shadow: 0px 0px 20px black;
}
.card-img {
  width: 100%;
}
.card-title {
  padding: 10px;
  display: inline-block;
  font-family: Open Sans;
  text-align: center;
  width: 100%;
}
<div class="card">
  <img class="card-img" src="http://prww-weather.com/logo.png" />
  <p class="card-title">Card Title</p>
</div>
链接地址: http://www.djcxy.com/p/29432.html

上一篇: 内容之间的空行

下一篇: 100%宽度延伸过父元素